Golang: [] byte (string) vs [] byte (* string)

I am curious why Golang does not provide a method []byte(*string)

. From a performance standpoint, won't []byte(string)

make a copy of the input argument and add a lot of cost (although that seems odd since strings are immutable, why copy them)?

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

+2


source to share


2 answers


[]byte("something")

is not a function (or method) call, it is of type conversion .

The self conversion does not copy the value. However, converting a string

to []byte

, and this is necessary because the slice of the result byte is mutable and if no copy is made, you can change / change the value string

(content string

), which is immutable, it should be like Spec: String types :

Strings are immutable: once created, the contents of a string cannot be changed.

Note that in cases where the conversion string

<=> []byte

is not satisfied, not satisfied, since it is optimized compiler. These are rare and "hard-coded" cases where there is evidence that an immutable string

cannot / will not change.

An example like this is looking for a value from a map, where is the key type string

, and you index the map using []byte

, converted to string

, of course (:



key := []byte("some key")

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

      

Another optimization is choosing a byte range of a string

, which is explicitly converted to a byte chunk:

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

      

(Note that without conversion, it for range

will iterate over the rune

string, not its UTF8-encoded bytes.)

+13


source


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

Because it doesn't make sense.

A pointer (for any type) cannot be represented (in any explicitly meaningful way) as []byte

.



From a performance standpoint, wouldn't [] bytes (string) make a copy of the input argument and add more value (although that seems odd since strings are immutable, why copy them)?

Conversion from []byte

to string

(and vice versa) involves copy because strings are immutable, but byte arrays are not.

However, using a pointer will not solve this problem.

+2


source







All Articles