#5 Go 关键字

2020-12-05

25 个关键字

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var

声明 (4)

  1. var 变量
  2. const 常量
  3. type 类型
  4. func 函数

并发相关 (3)

  1. go 并发
  2. chan 信道
  3. select 分支

类型 (3)

  1. interface 接口
  2. map 映射
  3. struct 结构体

流程控制 (3 + 4 + 6)

  1. defer 延迟执行
  2. goto 跳转
  3. return 返回

循环 (4)

  1. for
  2. continue
  3. break
  4. range 用于读取 slice、map、channel 数据

分支 (6)

  1. if
  2. else
  3. switch
  4. case
  5. default
  6. fallthrough

包 (2)

  1. package
  2. import

39 个预定义标识符

Types:
    any bool byte comparable
    complex64 complex128 error float32 float64
    int int8 int16 int32 int64 rune string
    uint uint8 uint16 uint32 uint64 uintptr

Constants:
    true false iota

Zero value:
    nil

Functions:
    append cap close complex copy delete imag len
    make new panic print println real recover

值 (4)

  1. true
  2. false
  3. iota
  4. nil

类型 (20 + 2)

int (10)

  1. int
  2. int8
  3. int16
  4. int32
  5. int64
  6. uint
  7. uint8
  8. uint16
  9. uint32
  10. uint64

complex (2)

  1. complex64
  2. complex128

float (2)

  1. float32
  2. float64

字符与字符串 (3)

  1. byte => uint8
  2. rune => int32
  3. string

泛型相关 (2) Go1.18+

  1. any
  2. comparable

其他 (3)

  1. bool
  2. uintptr 指针
  3. error 一个内置的 interface

Builtin 函数 (15)

  1. append
  2. delete
  3. close

  4. cap

  5. len

  6. copy

  7. make

  8. new

  9. panic

  10. recover

  11. print

  12. println

  13. real

  14. imag
  15. complex

#4 Go 模板

2020-12-01

fmt.Sprintf 字符串格式化

tpl := `[%s] Your verify code is %s.`
s := fmt.Sprintf(tpl, "Markjour", "1234")
println(s)

os.Expand 变量替换

tpl := `[${sign}] Your verify code is ${code}.`
params := map[string]string{"sign": "Markjour", "code": "1234"}
println(os.Expand(tpl, func(k string) string { return params[k] }))

text/template 和 html/template

这两个就可以处理复杂的情况,嵌套模板,控制语句都支持。

package main

import (
    "os"
    "text/template"
)

func main() {
    tpl := `[{{.sign}}] Your verify code is {{.code}}.`
    t := template.New("just-a-name")
    t, _ = t.Parse(tpl)
    params := map[string]string{"sign": "Markjour", "code": "1234"}
    t.Execute(os.Stdout, params)
}

附:strings.Map / bytes.Map 提供单个字符的替换

func Map(mapping func(rune) rune, s string) string
package main

import (
    "fmt"
    "strings"
)

const A = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \n"
const B = "N'|&4:@ j{BI+Y!H/Q_iR\\FM}$moLe?#X\"WCE3S,8(r1f%T.;6DbaG]y`q~ltJxu-k2gA\nvhnd=)*s7Z5p^OK[V0z>9<UcwP"

func main() {
    encrypt := func(r rune) rune {
        if !strings.ContainsRune(A, r) {
            return 0
        }
        return rune(B[strings.IndexRune(A, r)])
    }
    decrypt := func(r rune) rune {
        if !strings.ContainsRune(B, r) {
            return 0
        }
        return rune(A[strings.IndexRune(B, r)])
    }

    raw := "Life was like a box of chocolate, you never know what you're gonna get."
    fmt.Println(raw)

    encrypted := strings.Map(encrypt, raw)
    fmt.Println(encrypted)
    // 3j:4wFN_wIjB4wNw'!Mw!:w| !|!INi4dw}!RwY4\4QwBY!FwF Niw}!RAQ4w@!YYNw@4i)

    decrypted := strings.Map(decrypt, encrypted)
    fmt.Println(decrypted)
}

参考资料与拓展阅读

#3 Golang: cannot assign to struct field xxx in map

2020-11-20
package main

import (
    "fmt"
)

type Person struct {
    FirstName string
    LastName  string
}

func main() {
    // 准备 =========================
    people := make(map[int]Person)
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
    }
    people[1] = person

    // 报错:cannot assign to struct field people[1].FirstName in map
    // people[1].FirstName = "Jim"

    // 方式 1
    p := people[1]
    p.FirstName = "Alice"
    people[1] = p
    fmt.Println(people)
    // map[1:{Alice Doe}]
    fmt.Println(people[1])
    // {Alice Doe}

    // if p, ok := people[1]; ok {
    //  p.Field = 5
    //  people[1] = p
    // }

    // 方式 2
    people2 := make(map[int]*Person)
    people2[1] = &person
    people2[1].FirstName = "Adam"
    fmt.Println(people2)
    // map[1:0xc000060020]
    fmt.Println(people2[1])
    // &{Adam Doe}
}

总之,不能直接通过 key 找到 value(struct),然后修改其中的一个字段。

#2 Golang 数据类型

2020-10-31

基础类型:

  • Boolean types (bool)
  • Numeric types
  • String types (string)

复合类型:

  • Array types ([len]Type)
  • Slice types ([]Type)
  • Struct types (struct)
  • Map types (map[KeyType]ValueType{})

特殊类型:

  • Pointer types (*Type) 指针
  • Function types (func) 函数
  • Interface types (interface) 接口
  • Channel types (chan) 通道

引用类型

基础类型 + Array + Struct 不是引用类型,其他几种(Slice + Map + Pointer + Function + Interface + Channel)都是引用类型,函数传参的时候需要记住这一点。

数值

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

// 实现相关:
uint     either 32 or 64 bits
int      same size as uint
uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value

声明

var foo int

var foo int = 1

foo := 1

const foo = 1

const foo int = 1

注意:只有基础类型可以声明为常量。

#1 Golang 速查表

2020-06-26

1. 环境配置与基础语法

  • 目标:搭建开发环境,掌握基本语法和编程逻辑。
  • 内容:
    • 安装 Go 版本(推荐 Go 1.21+)及 IDE(如 VS Code + Go 插件、IntelliJ IDEA)。
    • 变量与数据类型(整型、浮点型、布尔型、字符串、数组、切片、字典)。
    • 运算符(算术、关系、逻辑、位运算)。
    • 流程控制(if-elseforswitchgoto)。
    • 函数与方法(函数定义、参数传递、返回值、闭包)。
  • 练习:
    • 编写计算器、斐波那契数列生成器。
    • 实现一个简易的 Todo List 管理工具。

2. 面向对象与结构体

  • 目标:理解 Golang 的 OOP 模型。
  • 内容:
    • 结构体(struct)的定义与初始化。
    • 方法(Method)的绑定(值接收者 vs 指针接收者)。
    • 接口(interface)与类型断言。
    • 组合(Composition)代替继承。
  • 练习:
    • 设计一个动物 kingdom,包含不同动物的行为(如 Dog 吠叫、Bird 飞翔)。
    • 实现一个简单的电商商品库存管理系统。

3. 并发与 Goroutine

  • 目标:掌握 Golang 的并发编程模型。
  • 内容:
    • Goroutine 的启动与停止(go func())。
    • Channel 的使用(阻塞、非阻塞、缓冲区)。
    • select 语句实现多路复用。
    • sync.Mutexatomic 包(锁与原子操作)。
  • 练习:
    • 实现一个多线程的 Web 服务器,处理并发请求。
    • 模拟生产者-消费者问题,使用 Channel 通信。

4. 标准库实战

  • 目标:熟悉 Golang 核心库,快速开发实际应用。
  • 内容:
    • 网络编程:net/http(REST API)、net/url(URL 解析)。
    • 数据处理:encoding/json/xml(序列化/反序列化)、sort/math(常用算法)。
    • 文件 I/O:os/path/filepath(文件操作)、io/ioutil(批量读写)。
    • 模板引擎:html/template(生成动态 HTML)。
  • 项目:
    • 构建一个 RESTful API(用户管理、文章发布)。
    • 开发一个命令行工具(如文件压缩/解压、天气查询)。

5. 微服务与框架

  • 目标:掌握企业级开发模式与流行框架。
  • 内容:
    • 微服务架构(服务拆分、API 网关、配置中心)。
    • 使用框架:Gin(轻量级 HTTP 框架)、EchoBeego
    • 分布式工具:etcd(键值存储)、Consul(服务发现)。
    • 容器化与 Docker(部署 Go 应用)。
  • 项目:
    • 设计一个电商系统,包含用户服务、订单服务、支付服务。
    • 实现一个实时聊天室(WebSocket + Goroutine)。

6. 数据库与 ORM

  • 目标:连接数据库并高效操作。
  • 内容:
    • SQL 数据库驱动(database/sql + PostgreSQL/MySQL)。
    • ORM 工具:GORMsqlx
    • NoSQL 支持(MongoDB + mgo 包)。
  • 项目:
    • 开发一个博客系统(支持 MySQL 存储、标签分类)。
    • 实现一个用户登录注册系统(JWT 认证 + Redis 会话)。

7. 工程化实践

8. 性能与调优

  • 目标:提升代码性能与稳定性。
  • 内容:
    • 性能分析工具:pproftrace
    • 优化技巧:减少内存分配、利用缓存、并发优化。
    • 错误处理与日志(log 包、zap 日志库)。
  • 实战:
    • 分析高并发场景下的性能瓶颈(如百万级请求处理)。
    • 重构代码,优化响应时间与资源占用。