这段golang代码是做什么的?

huangapple go评论110阅读模式
英文:

What does this golang code do?

问题

这行代码是为了确保 DropletsServiceOp 类型实现了 DropletsService 接口。在Go语言中,如果一个类型声明了一个接口,但没有实现该接口的所有方法,编译器会报错。通过将实例赋值给 _ 变量,可以确保编译器检查 DropletsServiceOp 是否实现了 DropletsService 接口,但不会使用该变量。这样可以避免编译器报错,同时确保代码的正确性。

英文:

I was reading DigitalOcean's golang client. I noticed that they create an instance of their *Op struct in a _ variable. Example:
https://github.com/digitalocean/godo/blob/master/droplets.go#L32

var _ DropletsService = &DropletsServiceOp{}

Why is this line needed?

答案1

得分: 10

这行代码是一个编译时检查,用于确认*DropletsServiceOp是否满足DropletsService接口的要求。

这行代码对程序的执行没有影响。

英文:

This line is a compile time check that *DropletsServiceOp satisfies the DropletsService interface.

The line has no effect on the execution of the program.

答案2

得分: 3

如果你查看那个文件的责任,那一行,你会得到一个线索:

https://github.com/digitalocean/godo/blame/master/droplets.go#L32

它在编译时检查*DropletsServiceOp是否满足DropletsService接口。在引入这个提交之前,他们在他们的测试套件中进行了这个检查。

英文:

If you look at the blame on that file, at that line, you get a clue:

https://github.com/digitalocean/godo/blame/master/droplets.go#L32

It does a compile-time check that *DropletsServiceOp satisfies the DropletsService interface. Prior to the commit introducing that, they were doing this in their test suite.

huangapple
  • 本文由 发表于 2016年1月2日 06:51:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/34560833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定