教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Go接口(Interface)的使用方法

Go接口(Interface)的使用方法

发布时间:2021-04-17   编辑:jiaochengji.com
教程集为您提供Go接口(Interface)的使用方法等资源,欢迎您收藏本站,我们将为您提供最新的Go接口(Interface)的使用方法资源
Go 语言不是一种 “传统” 的面向对象编程语言:它里面没有类和继承的概念。这是多态的Go版本.
demo_1.go在 main()方法中创建了一个 Square 的实例。在主程序外边定义了一个接收者类型是 Square 方法的 Area() ,用来计算正方形的面积:结构体 Square 实现了接口 Shaper 。所以可以将一个 Square 类型的变量赋值给一个接口类型的变量: areaIntf = sq1 。现在接口变量包含一个指向 Square 变量的引用,通过它可以调用 Square 上的方法 Area() 。当然也可以直接在Square 的实例上调用此方法,但是在接口实例上调用此方法更令人兴奋,它使此方法更具有一般性。接口变量里包含了接收者实例的值和指向对应方法表的指针。这是 多态 的 Go 版本,多态是面向对象编程中一个广为人知的概念:根据当前的类型选择正确的方法,或者说:同一种类型在不同的实例上似乎表现出不同的行为。

1.demo_1.go
package main
import "fmt"

type Shaper interface {//定义接口
	Area() float32
}

type Square struct {//结构体
	side float32
}

func (sq *Square) Area() float32 {//接口方法
	return sq.side * sq.side
}

func main() {
	sq1 := new(Square)//new一个结构体对象
	sq1.side = 5

	var areaIntf Shaper//接口
	//areaIntf = sq1 //方式一
	areaIntf = Shaper(sq1) //方式二
	fmt.Printf("The square has area: %f\n", areaIntf.Area())
}

2.demo_2.go
package main
import "fmt"

type Shaper interface {//接口定义
	Area() float32}

type Square struct {//正方形结构体
	side float32}
func (sq *Square) Area() float32 {//正方形接口实现
	return sq.side * sq.side}

type Rectangle struct {//矩形结构体
	length, width float32}
func (r Rectangle) Area() float32 {//矩形接口实现
	return r.length * r.width}
//add by begin
type Test struct{
	x,y float32}
func (m Test) Area() float32{
	return m.x   m.y}
//add end

func main() {
	r := Rectangle{5, 3} // Area() of Rectangle needs a value
	q := &Square{5}      // Area() of Square needs a pointer
	//add by
	o := Test{4,7}
	shapes := []Shaper{r, q,o}

	fmt.Println("Looping through shapes for area ...")

	for n := range shapes {
		fmt.Println("n======> ", n)
		fmt.Println("Shape details: ", shapes[n])
		fmt.Println("Area of this shape is: ", shapes[n].Area())
	}
}

3.demo_3.go
package main
import "fmt"
type stockPosition struct {
	ticker string
	sharePrice float32
	count float32
}

func (s stockPosition) getValue() float32 {
	return s.sharePrice * s.count
}

type car struct {
	make string
	model string
	price float32
}

func (c car) getValue() float32 {
	return c.price
}

type valuable interface {
	getValue() float32
}

func showValue(asset valuable) {
	fmt.Printf("Value of the asset is %f\n", asset.getValue())
}

func main() {
	var o valuable = stockPosition{"GOOG", 577.20, 4}
	showValue(o)
	o = car{"BMW", "M3", 66500}
	showValue(o)
}

到此这篇关于“Go接口(Interface)的使用方法”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
2020-10-18Go语言接口
Go 之 interface接口理解
Go 接口应用场景、注意事项和使用细节
关于golang面向接口
Go语言接口interface
20.不要在函数参数中使用空接口
【Golang】go语言面向接口
interface作为struct field,谈谈golang结构体中的匿名接口
19小接口的妙用
Go语言空接口类型(interface{})

[关闭]
~ ~