Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to fixed size byte array in Go

Tags:

go

Is there convenient way for initial a byte array?

package main import "fmt" type T1 struct {   f1 [5]byte  // I use fixed size here for file format or network packet format.   f2 int32 } func main() {   t := T1{"abcde", 3}   // t:= T1{[5]byte{'a','b','c','d','e'}, 3} // work, but ugly   fmt.Println(t) } 

prog.go:8: cannot use "abcde" (type string) as type [5]uint8 in field value

if I change the line to t := T1{[5]byte("abcde"), 3}

prog.go:8: cannot convert "abcde" (type string) to type [5]uint8

like image 456
Daniel YC Lin Avatar asked Nov 07 '11 16:11

Daniel YC Lin


2 Answers

You could copy the string into a slice of the byte array:

package main import "fmt" type T1 struct {   f1 [5]byte   f2 int } func main() {   t := T1{f2: 3}   copy(t.f1[:], "abcde")   fmt.Println(t) } 

Edit: using named form of T1 literal, by jimt's suggestion.

like image 109
SteveMcQwark Avatar answered Sep 22 '22 20:09

SteveMcQwark


Is there any particular reason you need a byte array? In Go you will be better off using a byte slice instead.

package main import "fmt"  type T1 struct {    f1 []byte    f2 int }  func main() {   t := T1{[]byte("abcde"), 3}   fmt.Println(t) } 
like image 24
jimt Avatar answered Sep 21 '22 20:09

jimt