结构体的嵌入类型
1,嵌入结构体1
package 主要 import “fmt” type Person  struct { name 字符串 } type Student  struct { int class person person ,,,,,,,,//定义person 类型为的人 } func main () { s :=,学生{1人{"小明"}} fmt.Println (“name :“s.person.name),,//访问嵌入结构体的变量 }//执行结果: name :小明
2,嵌入结构体2
package 主要 import “fmt” type Person  struct { name 字符串 } type Student  struct { int class Person ,,,,,,,,,//我们直接将人引入到学生 } func main () { s :=,学生{1人{"小明"}} fmt.Println (“name :“s.name),,//访问时可以直接访问s.name 而不需要s.person.name }//执行结果: 名称:,小明
接口
1,定义接口
在去语言中,接口是定义了类型一系列方法的列表,如果一个类型实现了该接口所有的方法,那么该类型就符合该接口
package 主要 import “fmt” import “数学” type Shape  interface { 面积()float64 } type Rectangle  struct { width float64 height float64 } type Circle  struct { radius float64 } func (r 矩形),区域(),float64 { return r.height * r.width } func (c 圆),区域(),float64 { return math.Pi *, math.Pow (c.radius, 2) } func getArea (shape 形状),float64 { return shape.area () } func main () { r :=,矩形{20、10} c :=,圆{4} fmt.Println (“Rectangle Area =", getArea (r)) fmt.Println (“Circle Area =", getArea (c)) }//执行结果: Rectangle Area =200 Circle Area =,
50.26548245743669 2,接口嵌入
package 主要 import “fmt” import “数学” type Shape  interface { 面积()float64 } type MultiShape  interface { Shape ,,,,,,,,,,,//嵌入式 } type Rectangle  struct { width float64 height float64 } type Circle  struct { radius float64 } func (r 矩形),区域(),float64 { return r.height * r.width } func (c 圆),区域(),float64 { return math.Pi *, math.Pow (c.radius, 2) } func getArea (shape MultiShape), float64 {,,,,,,,//改为MultiShape return shape.area () } func main () { r :=,矩形{20、10} c :=,圆{4} fmt.Println (“Rectangle Area =", getArea (r)) fmt.Println (“Circle Area =", getArea (c)) }//执行结果: Rectangle Area =200 Circle Area 50.26548245743669=,,,,,,,,,//执行结果一致