%n.mg 用于表示数字 n 并精确到小数点后 m 位,除了使用 g 之外,还可以使用 e 或者 f,例如:使用格式化字符串 %5.2e 来输出 3.4 的结果为 3.40e+00。
%p 指针的格式化字符
数组去重
go env -w 通过这种方式设置的参数是直接修改的GOENV路径下的env文件,再使用export的方式就无效
移除依赖,项目初始化
当前代码中不需要了某些包,删除相关代码片段后并没有在 go.mod 文件中自动移出。
运行下面命令可以移出所有代码中不需要的包:
1
go mod tidy
如果仅仅修改 go.mod 配置文件的内容,那么可以运行 go mod edit --droprequire=path,比如要移出 golang.org/x/crypto 包
1
go mod edit --droprequire=golang.org/x/crypto
结构体不同的初始化的方式new的使用
new返回的是指针,下面三种初始化方式是一样的
1 2 3 4 5 6 7
type User struct{ age int } var a=User{age:12} // 声明变量a为User类型,并且赋值初始值为12 var b=new(User) // 声明变量b为User类型的指针,也就是User类型的实例 var c User // 声明变量c为User类型,且值为空 这里的值是系统自己给的 var d =User{} // 声明变量d为User类型,且值为空 这里的值声明为空,也是系统自己给的
func main() { var a Bb = new(Aa) if _, ok := a.(*Aa); ok { // 这里原来一直报红,是因为之前我用a.(Aa),提示我Aa没有Spean方法,这里可以静态检查到,因为a里面现在存到是new(Aa),也就是一个指针,然后调用a.(Aa),放入到类型就是一个值类型,值类型和指针类型
} /////////////////// type-switch 类型检测 var y Bb = new(Cc) switch y.(type) { case *Cc: fmt.Println("wawawa") case *Aa: fmt.Println("ieieie") case nil: fmt.Println("baocuol") default: fmt.Println("default") } }
type Aa struct { } type Cc struct{}
func (a *Aa) Spean() { fmt.Println("haha") } func (a *Cc) Spean() { fmt.Println("haha") }
type Bb interface { Spean() }
接口变量的本质是指针
Linux下编译Mac, Windows平台的64位可执行程序:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build test.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build test.go
funcmain() { // Version A: items := make([]map[int]int, 5) for i:= range items { items[i] = make(map[int]int, 1) items[i][1] = 2 } fmt.Printf("Version A: Value of items: %v\n", items)
// Version B: NOT GOOD! items2 := make([]map[int]int, 5) for _, item := range items2 { item = make(map[int]int, 1) // item is only a copy of the slice element. item[1] = 2// This 'item' will be lost on the next iteration. } fmt.Printf("Version B: Value of items: %v\n", items2) }
输出结果:
1 2
Version A: Value of items: [map[1:2] map[1:2] map[1:2] map[1:2] map[1:2]] Version B: Value of items: [map[] map[] map[] map[] map[]]
需要注意的是,应当像 A 版本那样通过索引使用切片的 map 元素。在 B 版本中获得的项只是 map 值的一个拷贝
而已,所以真正的 map 元素没有得到初始化。