接口或结构体的嵌套(struct,interface)

1、结构体的嵌套一

package main
import "fmt"

type Person struct {
	name string
}

type Student struct {
	class int
	person Person         //定义person 类型为Person
}


func main(){
	s := Student{1,Person{"xiaoming"}}
	fmt.Println("name :",s.person.name)  //访问嵌入结构体的变量

}

//执行结果:
//name : xiaoming

2、结构体的嵌套二

package main
import "fmt"

type Person struct {
	name string
}

type Student struct {
	class int
	Person          //我们直接将Person引入到Student
}


func main(){
	s := Student{1,Person{"xiaoming"}}
	fmt.Println("name :",s.name)  //访问时可以直接访问s.name 而不需要s.person.name

}

//执行结果:
//name: xiaoming

3、接口嵌套(定义)

定义接口,在go语言中,接口是定义了类型一系列方法的列表,如果一个类型实现了该接口所有的方法,那么该类型就符合该接口

package main

import "fmt"
import "math"


type Shape interface {
	area() float64

}

type Rectangle struct {
	width float64
	height float64
}

type Circle struct {
	radius float64
}

func (r Rectangle) area() float64 {
	return r.height * r.width
}

func (c Circle) area() float64 {
	return math.Pi * math.Pow(c.radius,2)
}

func getArea(shape Shape) float64 {
	return shape.area()
}

func main(){
	r := Rectangle{20,10}
	c := Circle{4}
	fmt.Println("Rectangle Area =",getArea(r))
	fmt.Println("Circle Area =",getArea(c))

}

//执行结果:
//Rectangle Area = 200
//Circle Area = 50.26548245743669

4、接口嵌套

package main

import "fmt"
import "math"


type Shape interface {
	area() float64

}

type MultiShape interface {
	Shape            //嵌入式
}

type Rectangle struct {
	width float64
	height float64
}

type Circle struct {
	radius float64
}

func (r Rectangle) area() float64 {
	return r.height * r.width
}

func (c Circle) area() float64 {
	return math.Pi * math.Pow(c.radius,2)
}

func getArea(shape MultiShape) float64 {        //改为MultiShape
	return shape.area()
}

func main(){
	r := Rectangle{20,10}
	c := Circle{4}
	fmt.Println("Rectangle Area =",getArea(r))
	fmt.Println("Circle Area =",getArea(c))

}

//执行结果:
//Rectangle Area = 200
//Circle Area = 50.26548245743669        //执行结果一致

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值