Go语言常见的点
Contents
map 引用不存在的键名不会报错
map 引用不存在的键名不会报错,返回所属类型的默认值
m := make(map[int]int)
m[10] = 14
fmt.Println("exists key value:", m[10])
fmt.Println("not exists key value:", m[1])
// result:
// exists key value: 14
// not exists key value: 0
range遍历map不会按输入顺序输出,而是随机输出
m := map[int]int{
1: 10,
2: 20,
3: 30,
}
for i := 0; i < 2; i++ {
fmt.Println("scan times :", i)
for i, v := range m {
fmt.Println("key:", i, "value", v)
}
fmt.Println("")
}
// result:
// scan times : 0
// key: 3 value 30
// key: 1 value 10
// key: 2 value 20
//
// scan times : 1
// key: 1 value 10
// key: 2 value 20
// key: 3 value 30
指针参数赋值地址不改变外部变量
指针传参只是将指针的地址赋值给方法内的变量,此变量重新赋值新地址,只会改变方法内变量的指向,而不会改变外部对应变量的地址值。
type Person struct {
Name string
Age int64
}
func main() {
a := &Person{Age: 10}
example(a)
fmt.Println("example1 result:", a)
b := &Person{Age: 10}
example2(b)
fmt.Println("example2 result:", b)
var number, number2 int64 = 10, 10
var c, d *int64 = &number, &number2
example3(c)
fmt.Println("example3 result:", *c)
example4(d)
fmt.Println("example4 result:", *d)
}
func example(p *Person) {
p = &Person{
Name: "张三",
Age: 20,
}
}
func example2(p *Person) {
p.Age = 30
p.Name = "李四"
}
func example3(p *int64) {
var number int64 = 200000
p = &number
}
func example4(p *int64) {
var number int64 = 300000
*p = number
}
// result:
// example1 result: &{ 10}
// example2 result: &{李四 30}
// example3 result: 10
// example4 result: 300000
Author standsun
LastMod 2017-05-02