英文:
Interface implementation enforcement in Go
问题
我有一个简单的Go代码:
type MyInterface interface {
Do()
}
type Doer struct{}
func (d *Doer) Do() {}
// 选项1
var _ MyInterface = (*Doer)(nil)
// 选项2
var _ MyInterface = &Doer{}
相对于选项2,强制使用选项1(这在各个地方都被广泛使用和建议)有什么不足之处?
如果我们丢弃结果,使用实例化的实际对象而不是指针有什么坏处?
我理解选项2可能会慢一毫秒,因为它为结构体分配内存,还有另外一毫秒供垃圾回收清理,但所有这些只发生在启动时,并不影响运行时。
这些是我的正确理解吗?还是我漏掉了什么?
英文:
I have simple Go code:
type MyInterface interface {
Do()
}
type Doer struct{}
func (d *Doer) Do() {}
// Option 1
var _ MyInterface = (*Doer)(nil)
// Option 2
var _ MyInterface = &Doer{}
What is the downside of enforcing the interface with option 1 (which is widely used and advised everywhere) as opposed to option 2?
If we are discarding the result, what's the harm of instantiating a real object instead of pointer?
I understand that Option 2 is probably one millisecond slower as it does allocation of memory for the struct and also there is another millisecond for GC to clean it up probably, but all of it is happening only at startup and does not affect the runtime.
Are those my correct or do I miss anything?
答案1
得分: 3
问题中的分析很好。这里有两点补充:
选项1适用于任何类型。选项2只适用于具有复合字面语法的类型。
这是一个例子:
type IntDoer int
func (d *IntDoer) Do() {}
// 选项1
var _ MyInterface = (*IntDoer)(nil)
// 选项2 无法编译通过
var _ MyInterface = &IntDoer{}
选项2可能没有任何运行时的惩罚。编译器可能会优化掉分配操作。
英文:
The analysis in the question is good. Here are two additional points:
Option 1 works with any type. Option 2 only works for types with composite literal syntax.
Here's an example:
type IntDoer int
func (d *IntDoer) Do() {}
// Option 1
var _ MyInterface = (*IntDoer)(nil)
// Option 2 DOES NOT COMPILE
var _ MyInterface = &IntDoer{}
Option 2 may not have any runtime penalty. It's possible that the compiler optimizes out the allocation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论