[]byte(string) vs []byte(*string)
Asked Answered
A

2

6

I'm curious as why Go 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)?

Apollyon answered 18/4, 2017 at 10:57 Comment(1)
#14374134Apollyon
P
26

[]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.)

Picro answered 18/4, 2017 at 11:0 Comment(2)
Thanks for the quick reply. I forgot the fact that a byte slice is mutable, so a copy is needed. ThanksApollyon
FYI, there is a feature request for immutable byte array github.com/golang/go/issues/2205Apollyon
L
5

I'm curious as why Golang doesn't provide a []byte(*string) method.

Because it doesn't make sense.

A pointer (to any type) cannot be represented (in any obviously meaningful way) as a []byte.

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)?

Converting from []byte to string (and vice versa) does involve a copy, because strings are immutable, but byte arrays are not.

However, using a pointer wouldn't solve that problem.

Lentha answered 18/4, 2017 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.