20

Golang编程中遇到的小陷阱

 3 years ago
source link: https://studygolang.com/articles/30461
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1.int类型和float类型不能匹配

go语言规定不允许在整数型变量和浮点型变量之间进行任何数学运算。错误例子如下:

var n, m = 21, 2.1
    // 下面一行会报错:invalid operation: n / m (mismatched types int and float64)
    fmt.Println(n / m)

改正结果如下:

var n = 21 / 2.1
    fmt.Println(n)

2.int类型和time.Duration类型不能匹配

go语言规定数值运算的操作数必须具有相同的类型,除非该操作包含类型转换或非类型化常量。错误例子如下:

var n = 3
        // 下面一行会报错:invalid operation: timeout * time.Millisecond (mismatched types int and time.Duration)
    fmt.Println(n * time.Millisecond)

改正结果如下:

// 1. 使用常量
    const n = 3
    fmt.Println(n * time.Millisecond)
 
    // 2. 使用相同类型
    var n time.Duration = 10
    fmt.Println(n * time.Millisecond)

3.结构体struct

1)声明指针结构体时,如果未初始化,则初始值为nil,因此只有初始化后,才能访问字段或为字段赋值。例子如下:

type City struct {
    Name string
}
 
var c *City
// 错误用法, 未初始化, c为nil
c.Name = "Osaka" 
c = &City{}
// 初始化后,结构体指针指向某个结构体地址,才能访问字段,为字段赋值
c.Name = "Tokyo" 
 
// 因此,常用的做法如下
c := &City{}    
c.Name = "London"

2)使用Go内置new()函数,可以分配内存来初始化结构休,并返回分配的内存指针,因为已经初始化了,所以可以直接访问字段。例子如下:

var c = new(City)
c.Name = "NewYork"

其他诸如声明一个map不能立即赋值,类型断言失败会panic,二次关闭一个channel也会panic等比较常见的就暂时不详细介绍啦

有疑问加站长微信联系

iiUfA3j.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK