Go 18.0 专业五


01. 匿名字段

<h1>1. 接口</h1> <p><strong>go支持只提供类型而不写字段名的方式,也就是匿名字段,也称为嵌入字段</strong></p> <pre><code>package main import "fmt" // go支持只提供类型而不写字段名的方式,也就是匿名字段,也称为嵌入字段 //人 type Person struct { name string sex string age int } type Student struct { Person id int addr string } func main() { // 初始化 s1 := Student{Person{"5lmh", "man", 20}, 1, "bj"} fmt.Println(s1) s2 := Student{Person: Person{"5lmh", "man", 20}} fmt.Println(s2) s3 := Student{Person: Person{name: "5lmh"}} fmt.Println(s3) }</code></pre> <p>输出结果:</p> <pre><code> {{5lmh man 20} 1 bj} {{5lmh man 20} 0 } {{5lmh 0} 0 }</code></pre> <p><strong>同名字段的情况</strong></p> <pre><code>package main import "fmt" //人 type Person struct { name string sex string age int } type Student struct { Person id int addr string //同名字段 name string } func main() { var s Student // 给自己字段赋值了 s.name = "5lmh" fmt.Println(s) // 若给父类同名字段赋值,如下 s.Person.name = "枯藤" fmt.Println(s) }</code></pre> <p>输出结果:</p> <pre><code> {{ 0} 0 5lmh} {{枯藤 0} 0 5lmh}</code></pre> <p><strong>所有的内置类型和自定义类型都是可以作为匿名字段去使用</strong></p> <pre><code>package main import "fmt" //人 type Person struct { name string sex string age int } // 自定义类型 type mystr string // 学生 type Student struct { Person int mystr } func main() { s1 := Student{Person{"5lmh", "man", 18}, 1, "bj"} fmt.Println(s1) }</code></pre> <p>输出结果:</p> <pre><code> {{5lmh man 18} 1 bj}</code></pre> <p><strong>指针类型匿名字段</strong></p> <pre><code>package main import "fmt" //人 type Person struct { name string sex string age int } // 学生 type Student struct { *Person id int addr string } func main() { s1 := Student{&amp;Person{"5lmh", "man", 18}, 1, "bj"} fmt.Println(s1) fmt.Println(s1.name) fmt.Println(s1.Person.name) }</code></pre> <p>输出结果:</p> <pre><code> {0xc00005c360 1 bj} zs zs</code></pre>

页面列表

ITEM_HTML