Interface - 初探 Golang 中的接口(一)

栏目: Go · 发布时间: 4年前

内容简介:接口(interface ),是对其他类型行为的概括和抽象。假设对长方形、圆或者三角形等形状进行行为的概括和抽象,不难想到它们有一个共同的行为:在二维面求面积!不考虑它们是什么类型,我们在包

接口(interface ),是对其他类型行为的概括和抽象。

1. 类型行为的概括和抽象

假设对长方形、圆或者三角形等形状进行行为的概括和抽象,不难想到它们有一个共同的行为:在二维面求面积!

不考虑它们是什么类型,我们在包 shape.go 中定义一个接口,并用该接口 AreaTeller 作为参数实现了 TellArea 方法:

package shape

import "fmt"

type AreaTeller interface {
    Area() float64
}

func TellArea(at AreaTeller) {
    fmt.Printf("Hello, my area is %.2f\n", at.Area())
}

2. 接口的调用和实现

假设现在有一个长方形 R 和圆 C,让 shape 中的函数 TellArea 都可以把他们作为参数进行输出,即: shape.TellArea(R)shape.TellArea(C) 并预期得到我们想要的结果,该如何实现呢?

首先在 main.go 文件中,定义长方形和圆的结构描述:

type Rectangle struct {
    X, Y float64
}

type Circle struct {
    R float64
}

此时我们直接调用,直接报错:

package main

import (
    "github.com/alienrick/00_test/area"
)

type Rectangle struct {
    X, Y float64
}

type Circle struct {
    R float64
}

func main() {
    r := Rectangle{X: 3, Y: 4}
    shape.TellArea(r) // error

    c := Circle{R: 3}
    shape.TellArea(c) // error
}

因为 shape 包中的 AreaTeller 接口 Area() float 对所有形状的 求面积 行为进行抽象,假使让 AreaTeller 方法可以把长方形和圆作为参数传入,就必须实现 Area() float64 方法,如下:

func (r Rectangle) Area() float64 {
    return r.X * r.Y
}

func (c Circle) Area() float64 {
    return math.Pi * c.R * c.R
}

在 golang 的术语中,这就是 接口的隐式实现

package main

import (
    "math"

    "github.com/alienrick/00_test/shape"
)

type Rectangle struct {
    X, Y float64
}

func (r Rectangle) Area() float64 {
    return r.X * r.Y
}

func (c Circle) Area() float64 {
    return math.Pi * c.R * c.R
}

type Circle struct {
    R float64
}

func main() {
    r := Rectangle{X: 3, Y: 4}
    shape.TellArea(r)

    c := Circle{R: 3}
    shape.TellArea(c)
}

运行如上代码,得出结果:

Hello, my area is 12.00
Hello, my area is 28.27

3.扩展

假使现在来了一个三角形T,该怎么扩展呢?

type Square struct {
    X float64
}

func (t Square) Area() float64 {
    return t.X * t.X
} 

func main(){
    s := Square{X: 3}
    shape.TellArea(s) // Hello, my area is 9.00
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

构建高性能Web站点

构建高性能Web站点

郭欣 / 电子工业出版社 / 2012-6 / 75.00元

《构建高性能Web站点(修订版)》是畅销修订版,围绕如何构建高性能Web站点,从多个方面、多个角度进行了全面的阐述,几乎涵盖了Web站点性能优化的所有内容,包括数据的网络传输、服务器并发处理能力、动态网页缓存、动态网页静态化、应用层数据缓存、分布式缓存、Web服务器缓存、反向代理缓存、脚本解释速度、页面组件分离、浏览器本地缓存、浏览器并发请求、文件的分发、数据库I/O优化、数据库访问、数据库分布式......一起来看看 《构建高性能Web站点》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

随机密码生成器
随机密码生成器

多种字符组合密码

html转js在线工具
html转js在线工具

html转js在线工具