douzhu6149 2014-05-26 13:54
浏览 54
已采纳

为什么用Go接口{}作为参数,当我用字符串调用func时,它将强制转换一个alloc / ns吗?

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条回答 默认 最新

  • dt56449492 2014-05-26 14:02
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面