main.go
package main
import "fmt"
func main() {
rawString := "Hello World"
myStringBytes := fmt.Sprint([]byte(rawString))
myResultString := string([]byte(myStringBytes))
fmt.Println(myResultString)
fmt.Println(rawString)
}
Output
[72 101 108 108 111 32 87 111 114 108 100]
Hello World
Why myResultString still in bytes form?
How to convert the string of []bytes to []bytes?
I want myResultString == rawString
fmt.Sprint()will "render" the byte slice as a space separated list of decimal numbers (enclosed in square brackets). You can't convert that back to the originalstring, you have to split the decimal numbers and parse them (convert them to integers), assemble a byte slice from them and that you can convert back tostring. - iczamyResultStringlike that withfmt.Sprint, you cannot directly convert it back, because it is not the same data. That is not a standard serialization format, so you would need to manually convert back. - JimBfmt.Sprint()is not a conversion, it's a function call, which transforms your byte slice. You need the inverse transformation to get the original byte slice back, which you can then convert tostring. The standard lib has no builtin function for the inverse transformation offmt.Sprint()(when you pass a byte slice). - iczamyStringBytes = []byte(rawString)to getrawStringas a[]byte. UsemyResultString := string(myStringBytes)to convert that[]byteback to astring. - Cerise Limón