duankang5882 2017-04-18 10:57
浏览 177
已采纳

golang:[] byte(string)与[] byte(* string)

I'm curious as why Golang doesn't provide a []byte(*string) method. From a performance perspective, wouldn't []byte(string) make a copy of the input argument and add more cost (though this seems odd since strings are immutable, why copy them)?

I'm new to Go and would appreciate any clarification.

  • 写回答

2条回答 默认 最新

  • douwen5690 2017-04-18 11:00
    关注

    []byte("something") is not a function (or method) call, it's a type conversion.

    The type conversion "itself" does not copy the value. Converting a string to a []byte however does, and it needs to, because the result byte slice is mutable, and if a copy would not be made, you could modify / alter the string value (the content of the string) which is immutable, it must be as the Spec: String types section dictates:

    Strings are immutable: once created, it is impossible to change the contents of a string.

    Note that there are few cases when string <=> []byte conversion does not make a copy as it is optimized "away" by the compiler. These are rare and "hard coded" cases when there is proof an immutable string cannot / will not end up modified.

    Such an example is looking up a value from a map where the key type is string, and you index the map with a []byte, converted to string of course (source):

    key := []byte("some key")
    
    var m map[string]T
    // ...
    v, ok := m[string(key)]  // Copying key here is optimized away
    

    Another optimization is when ranging over the bytes of a string that is explicitly converted to a byte slice:

    s := "something"
    for i, v := range []byte(s) { // Copying s is optimized away
        // ...
    }
    

    (Note that without the conversion the for range would iterate over the runes of the string and not over its UTF8-encoded bytes.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?