GO 基础知识 - meetbill/chi GitHub Wiki
1 GoLang 中 & 与 * 的区别以及使用
&符号的意思是对变量取地址*符号的意思是对指针取值
func main() {
var a *int // 存储的是int的指针,目前为空
var b int = 4 // 存储的是int的值
a = &b // a 指向 b 的地址
a = b // a 无法等于 b,会报错,a是指针,b是值,存储的类型不同
fmt.Println(a) // a:0xc00000a090(返回了地址)
fmt.Println(*a) // *a:4(返回了值)
fmt.Println(*&a) // *抵消了&,返回了0xc00000a090本身
*a = 5 // 改变 a 的地址的值
fmt.Println(b) // b:5,改变后 b 同样受到改变,因为 a 的地址是指向 b 的
}
Go 语言只有值传递
1.1 传送门
2 Golang 构造函数
每个结构都值得拥有它的构造函数!你未来的自己会在下一次重构会议上感谢你 :blush:
Golang 作为结构化的语言是没有面向对象语言中的构造方法的,不过可以通过一些方式实现类似的面向对象语言中构造方法的效果。
因为 struct 是值类型,如果结构体比较复杂的话,值拷贝 性能开销会比较大,所以该构造函数返回的是结构体指针类型。
2.1 规范
New 关键字开头
返回结构体指针
2.2 示例
package main
import "fmt"
// 结构体
type dog struct {
name string
}
// NewDog 构造函数(值传递,不过传的值是个地址)
func NewDog(name string) *dog {
return &dog{
name: name,
}
}
// NewDog 构造函数(值传递,会多使用内存)
func NewDog2(name string) dog {
return dog{
name: name,
}
}
func main() {
d := NewDog("小明")
fmt.Println(d) // 输出:&{小明}
e := NewDog("小明2")
fmt.Println(e) // 输出:&{小明2}
fmt.Println(e.name) // 输出:小明
}
3 Channel
ch <- v // 发送值v到Channel ch中
v := <-ch // 从Channel ch中接收数据,并将数据赋值给v
4 GOPATH 和 GOROOT
- $GOPATH 是 go 的工程目录
- $GOROOT 是 go 的安装目录
5 Go Protobuf 序列化
protobuf 即 Protocol Buffers,是一种轻便高效的结构化数据存储格式
定义消息类型
接下来,我们创建一个非常简单的示例,student.proto
syntax = "proto3";
package main;
// this is a comment
message Student {
string name = 1;
bool male = 2;
repeated int32 scores = 3;
}
6 context
context.Background()
context.Background() 返回一个空的Context
7 格式化代码
gofmt -l -w xxx.go