英文:
Why with a Go interface{} as a parameter, when I call func with string, will it cast one alloc/ns?
问题
我有一个Go函数,它的参数是interface{}类型。当我用字符串调用该函数时,它会进行一次alloc/ns转换。为什么会这样?
func foo(...interface{}) error {
....
}
func use() {
var str = "use it"
e := foo(str)
_ = e
}
英文:
I have a Go function that has interface{} as a parameter. When I call the function with string, it will cast one alloc/ns. Why?
func foo(...interface{}) error {
....
}
func use() {
var str = "use it"
e := foo(str)
_ = e
}
答案1
得分: 5
在内部,接口变量是一个由两个字组成的结构。第一个字是指向变量动态类型信息的指针。第二个字要么包含变量的动态值(如果它可以放在一个字中),要么包含指向存储动态值的内存的指针(如果它更大)。
字符串变量比一个字大,因为它包含了长度和指向底层字符数据的指针。因此,将字符串存储在接口变量中涉及分配一些内存来保存该值。
英文:
Internally, an interface variable is a two word structure. The first word is a pointer to the information about the dynamic type of the variable. The second word will either (a) contain the variable's dynamic value if it will fit in a word, or (b) contain a pointer to memory holding the dynamic value if it is larger.
A string variable is larger than a word, since it holds both it's length and a pointer to the underlying character data. So storing a string in a an interface variable involves allocating some memory to hold that value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论