为什么当我将字符串作为参数调用函数时,会将其转换为一个alloc/ns?

huangapple go评论91阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年5月26日 21:54:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/23871796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定