温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

golang 结构体的嵌入类型和接口

发布时间:2020-07-30 08:16:13 来源:网络 阅读:4527 作者:欺世 栏目:开发技术

结构体的嵌入类型


1、嵌入结构体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、嵌入结构体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

接口


1、定义接口

在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

2、接口嵌入

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        //执行结果一致



向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI