遇到了, 小程序来练练手:
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}
但要注意, 这样是万万不行的:
package main
type Base struct {
bx int
by int
}
type Student struct {
b Base
x int
y int
}
func main() {
b := new(Base)
b = new(Student) // error
}
不多说。