go语言之进阶篇非结构体匿名字段

1、非结构体匿名字段

示例 :

package main

import "fmt"

type mystr string //自定义类型,给一个类型改名

type Person struct {
	name string //名字
	sex  byte   //性别, 字符类型
	age  int    //年龄
}

type Student struct {
	Person //结构体匿名字段
	int    //基础类型的匿名字段
	mystr
}

func main() {
	s := Student{Person{"mike", 'm', 18}, 666, "hehehe"}
	fmt.Printf("s = %+v
", s)

	s.Person = Person{"go", 'm', 22}

	fmt.Println(s.name, s.age, s.sex, s.int, s.mystr)
	fmt.Println(s.Person, s.int, s.mystr)

}

执行结果:

s = {Person:{name:mike sex:109 age:18} int:666 mystr:hehehe}
go 22 109 666 hehehe
{go 109 22} 666 hehehe

  

原文地址:https://www.cnblogs.com/nulige/p/10248921.html