Cannot convert string to [48]byte in golang

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

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.

2 Likes

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.

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

copy(siteNameAsSizedBytes[:], siteName)

fmt.Println(siteNameAsSizedBytes)

return siteNameAsSizedBytes

}

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.