Cannot convert string to [48]byte in golang


(sasi) #1

func SiteNameAsByte(siteName string) [48]byte {
b := [48]byte(siteName)
fmt.Println(b)
return b
}

I want to convert string to[]bytes is not showing error.

If I tried to work with string to [48]bytes…it is showing error cannot convert siteName (type string) to type [48]byte


(catacombs) #2

[]byte is a type. It’s not an array of bytes, if that’s how you’re interpreting it, and doesn’t need a size.


(Jay Poss) #3

I’m assuming you specifically want the result to be a 48 byte array.

stringBytes := []byte(siteName)   // convert input string to slice of bytes
var result [48]byte
copy( result[:], stringBytes )   // copy expects slice parameters, but the [:] tricks it I guess
return result  

I don’t use arrays much, but think this should work.


(Sean Killian) #4

Keep in mind that this passes the 48 byte array by value. If you really do want an array instead of just a slice, you might want to pass a pointer instead.


(sasi) #5

func ConvertSiteNameAsBytes(siteName string) [48]byte {
var siteNameAsSizedBytes [48]byte

copy(siteNameAsSizedBytes[:], siteName)

fmt.Println(siteNameAsSizedBytes)

return siteNameAsSizedBytes

}


(catacombs) #6

@sasikala, please format your code.


(Jay Poss) #7

You left out the convert string to []byte step. After reading the Go doc on copy, you are correct.