Menu
CoddyTech

隐式接口契约

Coddy 面向 C 开发者的 Go 课程的第 30 课,共 48 课。

C 语言的 struct 可以保存数据、函数指针和上下文指针,以组合行为。Go 通常通过接口值表达相同的依赖关系。Go 的接口实现是隐式的:方法集必须匹配。存储并调用传入的协作者,而不是将具体策略硬编码进去。

一个类型只要拥有接口所需的方法集,就实现了该接口;无需编写 implements 声明。接受一个小型接口,就能让调用方提供自己的行为。接口值包含一个动态的具体类型和值。如果行为需要可变的标识,请始终一致地使用指针接收者。

C 示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Policy { int (*cost)(int); };
int double_cost(int units) { return units * 2; }
int bill(const struct Policy *p, int units) { return p->cost(units); }
int main(void) {
    struct Policy p = {double_cost};
    printf("%d\n", bill(&p, 4));
    return 0;
}

源代码输出:

8

Go 示例

package main
import ("fmt")
type Speaker interface { Speak()string }; type Bell struct{}; func(Bell)Speak()string{return "ding"}
func main(){var s Speaker = Bell{}
fmt.Println(s.Speak())}

Go 输出:

ding
challenge icon

挑战

简单

定义接口 Transformer,其中包含 Transform(int) int;定义 Double,使其实现乘以 2 的功能;定义 Apply(t Transformer,n int) int,并调用它的方法。驱动程序会提供另一个实现来测试接口调用。

实现声明的 API,并返回结果,不要打印。驱动程序会检查必需的 API,并确保调用方的输入不变。集合的标准输出使用 Go 的方括号格式,而不是 JSON。

你的代码应放在 transformer.go、double.go、exercise.go 中。main.go 包含提供的输入和输出代码,不能编辑。代码都放在同一个扁平的 package main 中,不要再添加第二个 main。

亲手试试

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
type probeTransform struct{};func(probeTransform)Transform(n int)int{return n+7}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
must(Apply(probeTransform{},4)==11 && (Double{}).Transform(3)==6,"interface dispatch API");
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C 开发者的 Go中的所有课

自己练习: Go 在线编译器