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

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

内容简介:接口(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
}

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

查看所有标签

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

Learn Python 3 the Hard Way

Learn Python 3 the Hard Way

Zed A. Shaw / Addison / 2017-7-7 / USD 30.74

You Will Learn Python 3! Zed Shaw has perfected the world’s best system for learning Python 3. Follow it and you will succeed—just like the millions of beginners Zed has taught to date! You bring t......一起来看看 《Learn Python 3 the Hard Way》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

MD5 加密
MD5 加密

MD5 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具