Menu
CoddyTech

隐式接口约定

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

Ruby 中的组合通常依赖鸭子类型:只要协作者具有所需的方法,就可以使用。Go 通过接口表达这种预期,并检查类型的方法集。实现仍然是隐式的,不需要声明 implements。继续将调用转发给实际传入的对象。

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

Ruby 示例

class Rate
  def initialize(cents)
    @cents = cents
  end
  def cost(units)
    @cents * units
  end
end
class Bill
  def initialize(rate)
    @rate = rate
  end
  def total(units)
    @rate.cost(units)
  end
end
puts Bill.new(Rate.new(7)).total(2)

源代码输出:

14

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,并确保调用方的输入不被修改。集合的 stdout 使用 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自我测试

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

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

自己练习: Go 在线编译器