英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论