Go struct
命名结构体类型S不可以定义一个和自己拥有一样结构的类型的作为成员变量,但是可以定义一个指针。
package main 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 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 } func appendValues(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 }
注意:如果一个成员变量的首字母是大写可以导出,这也是一个特性。
函数中传值一般都是直接操作指针,下面是指针操作结构体几种方式
pp := &image.Point{2, 3} //pp 可以用下面两行的方式实现 qq := new(image.Point) *qq = image.Point{2, 3}
匿名成员
package main type Point struct { X, Y int } type Circle struct { Point Radius int } type Wheel struct { Point Spokes int } func main() { w := Wheel{ Point: Point{1, 2}, Spokes: 3, } c := Circle{ Point: Point{2, 3}, Radius: 2, } }
随笔而已,我还不认为自己有能写blog的水平。
一个没有高级趣味的人。
email:hushui502@gmail.com