go中struct的嵌套

版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/83867646

        遇到了, 小程序来练练手:

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}

       不多说。

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/83867646
今日推荐