GO struct的匿名字段

package main

import "fmt"

type Skills []string

type Human struct {

    name string

    age int

    weight int

}

type Student struct {

    Human // 匿名字段,那么默认struct就包含了Human的所有字段

    Skills //匿名字段,自定义的类型string slice

    int //内置类型作为匿名字段

    speciality string

}

func main() {

    jane := Student{Human: Human{"Jane", 35, 100}, speciality: "Biology"}

    fmt.Println("Her name is ", jane.name)

    fmt.Println("Her age is ", jane.age)

    fmt.Println("Her weight is ", jane.weight)

    fmt.Println("Her speciality is ", jane.speciality)

    jane.Skills = []string{"anatomy"}

    fmt.Println("Her skills are ", jane.Skills)

    fmt.Println("She acquired two new ones")

    jane.Skills = append(jane.Skills, "physics", "golang")

    fmt.Println("Her skills now are", jane.Skills)

    jane.int = 3

    fmt.Println("Her preferred number is ", jane.int)

}

输出结果为:

Her name is Jane

Her age is 35

Her weight is 100

Her speciality is Biology

Her skills are [anatomy]

She acquired two new ones

Her skills now are [anatomy physics golang]

Her preferred number is 3

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容