Go接口实例

Go支持在struct类型上定义的方法。area 方法有一个 * rect类型的接收器。可以为指针或值接收器类型定义方法。这里是一个值接收器的例子。
这里调用struct定义的2个方法。

接口是方法签名的命名集合。这里是几何形状(geometry)的基本接口。
对于这个例子,将在rectcircle类型上实现这个接口。

要在Go中实现一个接口,需要实现接口中的所有方法。 这里在rect上实现geometry的一个实例。

以及 circles 的实现。

如果变量具有接口类型,那么可以调用命名接口中的方法。这里是一个通用 measure() 函数,任何几何形状都有这个函数。

circlerect结构类型都实现了几何(geometry)接口,因此可以使用这些结构体的实例上调用measure()函数。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

structs.go的完整代码如下所示 -

package main

import "fmt"
import "math"

// Here's a basic interface for geometric shapes.
type geometry interface {
    area() float64
    perim() float64
}

// For our example we'll implement this interface on
// `rect` and `circle` types.
type rect struct {
    width, height float64
}
type circle struct {
    radius float64
}

// To implement an interface in Go, we just need to
// implement all the methods in the interface. Here we
// implement `geometry` on `rect`s.
func (r rect) area() float64 {
    return r.width * r.height
}
func (r rect) perim() float64 {
    return 2*r.width + 2*r.height
}

// The implementation for `circle`s.
func (c circle) area() float64 {
    return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
    return 2 * math.Pi * c.radius
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic `measure` function taking advantage of this
// to work on any `geometry`.
func measure(g geometry) {
    fmt.Println(g)
    fmt.Println(g.area())
    fmt.Println(g.perim())
}

func main() {
    r := rect{width: 3, height: 4}
    c := circle{radius: 5}

    // The `circle` and `rect` struct types both
    // implement the `geometry` interface so we can use
    // instances of
    // these structs as arguments to `measure`.
    measure(r)
    measure(c)
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run interfaces.go
{3 4}

{5}
78.53981633974483
31.41592653589793

上一篇:Go指针实例

下一篇:Go错误实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程