使用指针或值嵌入Go中 [英] Embedding in Go with pointer or with value
本文介绍了使用指针或值嵌入Go中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用指针和值嵌入golang中.通过指针
I can embed in golang with pointer and value. By pointer
type Bitmap struct{
data [4][4]bool
}
type Renderer struct{
*Bitmap
on uint8
off uint8
}
按值
type Bitmap struct{
data [4][4]bool
}
type Renderer struct{
Bitmap
on uint8
off uint8
}
通过指针或值更喜欢什么?
What is more prefer by pointer or value?
推荐答案
这要视情况而定.这里有几种可能性.
It depends. There are several possibilities here.
- 如果按值传递Renderer,并且在* Bitmap上定义了Bitmap所需的方法,则需要嵌入* Bitmap.
- 如果将Renderer作为指针传递,则可以将Bitmap嵌入为值,而不会出现任何问题(在这种情况下,仍然可以使用指针方法).
- 如果Bitmap具有返回指针的构造函数,并且Bitmap的零值不可用,则您将要嵌入* Bitmap,因为您不希望鼓励按值复制Bitmap值
- 如果所有位图方法都是值方法,那么您肯定要按值嵌入.
在特定情况下,由于类型较小,我可能会按值嵌入-它使您可以访问并减少内存分配.
In the specific case you have here, I'd probably embed by value, as the type is small - it gives you locality of access and less memory allocations.
这篇关于使用指针或值嵌入Go中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文