1
votes

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

1
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 original string, 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 to string. - icza
You formatted myResultString like that with fmt.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. - JimB
So basically fmt.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 to string. The standard lib has no builtin function for the inverse transformation of fmt.Sprint() (when you pass a byte slice). - icza
Thank you.. now im gonna try to make function to inverse transformation from string []bytes to []bytes - Haryo Bagas Assyafah
Use myStringBytes = []byte(rawString) to get rawString as a []byte. Use myResultString := string(myStringBytes) to convert that []byte back to a string. - Cerise Limón

1 Answers

1
votes

Just used this function to resolve this problem. Fyi, I used this method to parse semi colon query param from HTML request (:

package main

import (
   "fmt"
   "strconv"
   "strings"
)

func main() {
    rawString := "Hello World"
    myStringBytes := fmt.Sprint([]byte(rawString))
    
    myResultString, _ := string(StringBytesParseString(myStringBytes))

    fmt.Println(myResultString)
    fmt.Println(rawString)
}

func StringBytesParseString(byteString string) (string, error) {
    byteString = strings.TrimSuffix(byteString, "]")
    byteString = strings.TrimLeft(byteString, "[")
    sByteString := strings.Split(byteString, " ")
    var res []byte
    for _, s := range sByteString {
        i, err := strconv.ParseUint(s, 10, 64)
        if err != nil {
            return "", err
        }
        res = append(res, byte(i))
    }

    return string(res), nil
}