Menu
CoddyTech

隐式接口约定

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

C++ 组合可以拥有一个具体值,也可以引用一个多态依赖项。Go 接口允许使用者存储一个行为契约,并通过隐式方式实现它。确保提供的协作者可观察;在使用者内部构造首选的具体类型会破坏替换能力。

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

C++ 示例

#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
    struct Rate { int cents; int cost(int n) const { return cents * n; } };
    struct Bill { Rate rate; int total(int n) const { return rate.cost(n); } };
    Rate rate{4};
    Bill bill{rate};
    rate.cents = 7;
    std::cout << bill.total(2) << '\n';
}

源代码输出:

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 在线编译器