Go接口有哪些例子?

7 go

我发现了一篇关于Go 的有趣博客文章.

我试图理解接口的概念,但我发现很难从博客文章中的代码片段这样做,而且几乎不可能从语言规范中做到这一点.

任何人都可以在工作程序中指出一个简单的Go接口示例吗?

Von*_*onC 5

教程“ Go 中的接口 - 第 2 部分:辅助适应性、进化设计”(2012 年 1 月,来自Sathish VJ)清楚地提到了 Go 中接口的主要优势:

Go 的接口不是 Java 或 C# 接口的变体,而是更多。
它们是大规模编程和适应性进化设计的关键

请参阅同一篇文章中有关总线的不同视角(接口)的示例:

package main

import "fmt"

//Go Step 1: Define your data structures
type Bus struct {
    l, b, h int
    rows, seatsPerRow int
}

//Go Step 2: Define a real world abstraction that could use the data we structure we have
type Cuboider interface {
    CubicVolume() int
}

//Go Step 3: Implement methods to work on data
func (bus Bus) CubicVolume() int {
    return bus.l *  bus.b * bus.h
}

//Go step - repeat 2 & 3 for any other interfaces
type PublicTransporter interface  {
    PassengerCapacity() int
}

func (bus Bus) PassengerCapacity() int {
    return bus.rows * bus.seatsPerRow
}

func main() {
    b := Bus{
             l:10, b:6, h:3,
             rows:10, seatsPerRow:5}

    fmt.Println("Cubic volume of bus:", b.CubicVolume())
    fmt.Println("Maximum number of passengers:", b.PassengerCapacity())
}
Run Code Online (Sandbox Code Playgroud)

它似乎是以数据为中心的——首先定义你的数据,然后随着你的进展构建你的接口抽象。
这里的层次结构是“沿途”构建的,没有明确说明——根据与类型关联的方法签名,它被理解为实现特定的接口。

现在让我们假设,随着时间的推移,我们巴士的一些项目要求发生了变化——现在有一项新法律规定每位乘客至少应该有一定的最小立方体体积。
我们的总线现在必须坚持一个名为的新接口PersonalSpaceLaw,该接口不同于它已经实现的任何其他接口

//new requirement that the Bus must be compatible with
type PersonalSpaceLaw interface {
    IsCompliantWithLaw() bool
}

func (b Bus) IsCompliantWithLaw() bool {
    return (b.l * b.b * b.h) / (b.rows * b.seatsPerRow) >= 3
}
Run Code Online (Sandbox Code Playgroud)

功能已经扩展,核心类或核心层次结构没有任何改变。这种实现更加简洁,易于扩展,并且可以随着项目需求的变化而更好地扩展。

这是Go Playground 中完整工作程序

文章以 John Asmuth 引用的关于 Go 中接口生产力的线程结束:

“事实上,我不必花时间预先设计某种类型的层次结构,然后在完成之前将其重新排列两到三次。
这甚至不是容易做到正确
的事实-这是事实我只是不必担心它,可以继续使用实际的算法。


esm*_*esm 4

这是一个正在进行中的学习练习,当然也是一个良好风格的糟糕例子,但你就可以了规范)。

此外,作为一个更奇特的例子,我在 go-nuts 邮件列表上发表了一篇关于使用 interface{} 构建处理匿名数据的函数(在本例中为“三元运算”函数)的文章:

package main
import "fmt";
func Tern(exp bool, a interface{}, b interface{}) (interface{}) {
    if exp { return a }
    return b
}
func main() {
    a := 7; b := 1;
    result := Tern(a > b, a, b);
    fmt.Printf("%d\n", result);
}
Run Code Online (Sandbox Code Playgroud)