Go 常见严格格式汇总,struct,func...不定期更新!

1 引言

Golang对格式有着较为严格的规定,例如方法大括号一定要放在方法名后,否则编译不过;变量(常量除外)未使用,也编译不过等等

2 例子

2.1 struct

type person struct{
        name string
        age int
}
//OK
p:=person{
        name:"momo",
        age:18,
}
//OK
p:=person{
        name:"momo",
        age:18}

//syntax error: unexpected newline, expecting comma or }
p:=person{
        name:"momo",
        age:18
}

2.2 map

//编译成功
a := map[int]interface{}{}
aa :=make([]map[int]interface{},0)

//编译成功
b := map[int]string{}
bb :=make([]map[int]string,0)

//编译错误
c := map[int]string
cc :=make([]map[int]string,0)

//编译成功
x := []map[int]interface{}{{},{}}
y := make([]map[int]interface{},0)

//建议使用make函数,可以初始化大小  

2.3 map使用

//都OK
dict := make(map[string]int)
dict["one"] = 1
dict2 := map[string]int{}
dict2["one"] = 12

//申明为nil的map
var colors map[string]string
// 将Red 的代码加入到映射
colors["Red"] = "#da1337" //报错

2.4 待续...  

  

3 扩展资料

1.Golang开发者常见的坑