英文:
In Golang which type should I use for a method-only type?
问题
我是你的中文翻译助手,以下是翻译好的内容:
我指的是像这样的仅包含方法的类型:
var Util util
type util struct { }
func (util)Help(v VM) {}
func (util)HelpMe(v VM) {}
func (util)HelpYou(v VM) {}
func (util)HelpEveryOne(v VM) {}
我在binary.BigEndian中看到了这种用法:
// LittleEndian is the little-endian implementation of ByteOrder.
var LittleEndian littleEndian
// BigEndian is the big-endian implementation of ByteOrder.
var BigEndian bigEndian
type littleEndian struct{}
这是一种非常巧妙的方法来组织你的方法。所以问题是:为什么使用struct{}?为什么不只是一个int别名,选择struct{}而不是其他类型有什么原因吗?
英文:
I mean a method-only type like this
var Util util
type util struct { }
func (util)Help(v VM) {}
func (util)HelpMe(v VM) {}
func (util)HelpYou(v VM) {}
func (util)HelpEveryOne(v VM) {}
I see this in binary.BigEndian
// LittleEndian is the little-endian implementation of ByteOrder.
var LittleEndian littleEndian
// BigEndian is the big-endian implementation of ByteOrder.
var BigEndian bigEndian
type littleEndian struct{}
This is a very tricky way to group your method. So the question is: why struct{}? Why not just a int alias, is there any reason to choose struct{} over other types?
答案1
得分: 5
我相信struct {}和int之间的主要区别在于,struct {}不占用内存空间,而未使用的int会浪费4或8个字节。
英文:
I believe that the main difference between struct {} and int is that struct {} takes up no memory whereas an unused int would waste 4 or 8 bytes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论