go - 使用空接口(interface)或空结构作为映射的值有什么区别?

标签 go

我正在使用这个构造来模拟一个集合

type MyType uint8
map[MyType]interface{}

然后我添加我所有的键并将它们映射到 nil

我知道也可以使用

map[MyType]struct{}

使用空结构与 interface{} 相比的任何好处。

最佳答案

内存使用情况。例如,类型 struct{}interface{}bool

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    var s struct{}
    fmt.Println(unsafe.Sizeof(s))
    var i interface{}
    fmt.Println(unsafe.Sizeof(i))
    var b bool
    fmt.Println(unsafe.Sizeof(b))
}

输出(32 位架构的字节数):

0
8
1

输出(64 位架构的字节数):

0
16
1

引用资料:

Go Data Structures: Interfaces

关于go - 使用空接口(interface)或空结构作为映射的值有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770114/

相关文章:

go - 如何使用 go 服务(正确地)一个 react-router?

go - 在Golang中阅读BigQuery。并未给出所有预期结果。该怎么办?

google-app-engine - 尝试读取 *http.Response Body 时出现运行时错误,已使用 urlfetch.Transport

makefile - GNU Make 简单扩展变量和自动变量

database - 如何在Apache Cassandra中正确建模数据以允许通过两个唯一的不同字段进行查询

go - golang 中的空函数

macos - 在 OS X 中自动启动 godoc localhost 服务器?

go - 如何从 golang 中的处理程序服务器文件

go - 创建具有类型接口(interface)的映射以通过 URL 参数接受任意数据类型

docker - 戈兰 : Is it safe to say that if a struct implements a method then it satisfies all interfaces that define that method's signature?