type identifier struct {
field1 type1
field2 type2
...
}
复制代码
结构体得字段能够是任何类型,甚至是结构体自己,也能够是函数或者接口git
type Point struct { x, y int }
复制代码
new函数获取到得是结构体类型得指针github
使用new函数跟使用&T{}是等价的,都是产生结构体类型指针编程
获取结构体类型 编程语言
混合字面量语法ide
point1 := Point{0, 3} (A)
point2 := Point{x:5, y:1} (B)
point3 := Point{y:5} (C)
复制代码
结构体的类型定义在它的包中必须是惟一的,结构体的彻底类型名是:packagename.structname函数
point.x = 5
复制代码
x := point.x
复制代码
type myStruct struct { i int }
var v myStruct // v是结构体类型变量
var p *myStruct // p是指向一个结构体类型变量的指针
复制代码
结构体和它所包含的数据在内存中是以连续块的形式存在的布局
Go不支持面向对象编程语言中的构造方法,可是能够经过函数实现spa
type File struct {
fd int // 文件描述符
name string // 文件名
}
// 定义工厂方法,函数名大写字母开头才能被跨包调用
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
return &File{fd, name}
}
// 调用工厂方法
f := NewFile(10, "./test.txt")
复制代码
若是想要强制使用工厂函数,那么能够将结构体的类型改成首字母小写3d
结构体中的字段,除了名字和类型,还有一个可选的标签,它是附属在字段的字符串(至关于字段的解释)指针
type TagType struct { // tags
field1 bool "An important answer"
field2 string "The name of the thing"
field3 int "How much there are"
}
func main() {
tt := TagType{true, "Barak Obama", 1}
for i := 0; i < 3; i++ {
refTag(tt, i)
}
}
func refTag(tt TagType, ix int) {
// 使用reflect包
ttType := reflect.TypeOf(tt)
ixField := ttType.Field(ix)
fmt.Printf("%v\n", ixField.Tag)
}
复制代码
// 字段名称分别是:bool, string, int
type TagType struct {
bool
string
int
}
复制代码
在结构体中,对于每种数据类型,只能有一个匿名字段
Go语言的继承是经过内嵌或组合来实现的
结构体的属性首字母大写
type TagType struct {
Field1 bool
Field2 string
Field3 int
}
复制代码
入门教程推荐: github.com/Unknwon/the…