Go接口(Interface)的使用方法
2023-09-14 09:16:13 时间
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)
}
相关文章
- 12.Go语言-方法
- 《Go语言精进之路:从新手到高手的编程思想、方法和技巧1》7-9章笔记
- 【愚公系列】2022年08月 Go教学课程 033-结构体方法重写、方法值、方法表达式
- 如何优雅的通过Shell脚本一键部署GO项目到服务器 |Go主题月
- Go 编程语言的真正优势是什么?
- Go常见错误集锦之map
- 理解go中空结构体的应用和实现原理
- go test命令(Go语言测试命令)完全攻略
- Go基础–终端操作和文件操作详解编程语言
- Go语言组合和方法集
- 编程新精英:Go语言 Redis开发(go语言redis开发)
- Go 1.16 即将发布,这些变更你需要知道
- Go 通道是糟糕的,你应该也觉得很糟糕
- 简易教程:如何在 Linux 上安装 GO 语言(go语言安装linux)
- 关键字在SQL Server中利用GO关键字实现更优化的操作(sqlserver中go)
- 用Go语言深入Redis缓存技术(用go写redis)
- 请求简单而快速用Go编写的Redis请求测试(用go写的redis)
- 数据库Go语言连接Oracle数据库的指南(go如何连接oracle)
- 学习Oracle Go了解信息技术世界(oracle go的用法)