By Stefan Nilsson
The original url: yourbasic.org/golang/conv…
Basic cognitive
Converting between a string and a byte slice (an array) yields a brand new slice that contains the same bytes as the string and vice versa.
- Transformations do not modify the data
- The only difference is that strings are immutable, while byte slices can be modified
If you need to manipulate the rune of a string, you may need to convert the string to a rune slice. See runes and string interconversion in Golang for more details.
Slice a string into bytes
When you convert a string to a byte slice, you get a new slice containing the same bytes as the string.
b := []byte("ABC euro")
fmt.Println(b) // [65 66 67 226 130 172]
Copy the code
Note that the character €is encoded using 3-byte UTF-8. For more information on UTF-8 encoding of Unicode code points, see this article on RUNe.
Slicing bytes into strings
When you convert part of a byte to a string, you get a new string that contains the same bytes as the segment.
S := string([]byte{65, 66, 67, 226, 130, 172}) fmt.println (s) // ABC€Copy the code
performance
These transformations create a new slice or string, so the time complexity is proportional to the number of bytes processed.
Scan the QR code below to follow the Feed and regularly push the latest posts