定义
构造体是一种聚合的数据类型,由零个或多个任意类型的值聚合成的实体。
type Employee struct {    ID int    Name string    Address string    DoB time.time    Position string    Salary int    ManagerId int}    var dilbert Employee// 成员的赋值dilbert.Salary -= 50900postion := &dilbert.Position // 对成员取指针,而后通过指针拜访*position = "Senior" + *position 

一个命名为S的构造体类型不能在蕴含S类型的成员:因为一个聚合的值不能蕴含它本身。(该限度同样适宜用于数据)然而S类型的构造体能够蕴含*S指针类型的成员,这个让咱们创立递归的数据结构,比方链表和树。

type tree struct {    value int    left,right *tree}func sort(values []int) {    var root *tree    for _,v :=range values {        root = add(root,v)    }    appendValues(values[:0],root)}func appendValue(values []int,t *tree) []int {    if t != nil {        values = appendValues(values,t.left)        values = append(values,t.value)\        values = appendValues(values,t.right)    }    return values}func add(t *tree,value int) *tree {    if t==nil {        t = new(tree)        t.value = value        return t    }       if value < t.value {        t.left = add(t.left,value)    } else {        t.right = add(t.right,value)    }    return t}    
构造体字面值

构造体值也能够用构造体字面值示意,构造体字面值能够指定每个成员的值

type Point struct {X,Y int}p := Point{1,2}// 如果思考效率的话,较大的构造体通常会用指针的形式传入和返回func Bonus(e *Employee,percent int)int {    return e.Salary * percent / 100}    
创立构造体
pp := &Point{1,2}// 也能够上面这种pp := new(Point)*pp = Point{1,2}
构造体嵌入和匿名成员
type Circle struct {    X,Y,Radius int}type Wheel struct {    X,Y,Radius,Spokes int}

一个Circle代表的圆形类型蕴含了规范圆心的X和Y坐标信息,和一个Radius示意半径信息。一个 Wheel 轮型除了蕴含 Circle 类型所有的全副成员外,还减少了 Spokes 示意伸向辐条的数量。

var w Wheelw.X = 8w.Y = 8w.Raduis = 5w.Spokes = 20

随着库中几何形态的增多,咱们肯定会留神它们之间的类似和反复之处,所以咱们可能为了便于保护而将雷同的属性独立起来

type Point struct {    X,Y int}type Circle struct {    Center Point    Raduis int}type Wheel struct {    Circle Circle    Spokes int}var W Wheelw.Circle.Center.Center.X = 8w.Circle.Center.Center.Y = 8w.Circle.Raduis = 8W.Spokes = 20