go中struct的巢狀
阿新 • • 發佈:2018-11-10
遇到了, 小程式來練練手:
package main
import "fmt"
type Base struct {
bx int
by int
}
type Student struct {
b Base
x int
y int
}
func main() {
s := new(Student)
s.b.bx = 1
s.b.by = 100
s.x = 2
s.y = 3
s1 := Student{Base{1, 100}, 2, 3}
fmt.Println(s, s1)
}
結果:&{{1 100} 2 3} {{1 100} 2 3}
稍作修改:
package main import "fmt" type Base struct { bx int by int } type Student struct { Base x int y int } func main() { s := new(Student) s.bx = 1 s.by = 100 s.x = 2 s.y = 3 s1 := Student{Base{1, 100}, 2, 3} fmt.Println(s, s1) }
結果:&{{1 100} 2 3} {{1 100} 2 3}
不多說。