28

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

1

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

7 Comments

In this method, the copy work will delayed on runtime instead of compile time. Am I right?
@DanielYCLin:That is correct. The example shown here can also do without the [5]byte{} bit in the struct initializer. A fixed array struct field is already initialized. There is no need to do it twice: t := T1{f2: 3}; copy(t.f1[:], "abcde").
The copy can't happen at compile time in either case. In both cases, data will be copied onto the stack or into the heap from the program data. Also, while I would agree that the named form is nicer (I was considering using it, but decided not to), the array does not get initialized twice in the code I posted.
I think the fancy usage to assign "abcde" directly into [5]byte may NOT be modified by Go authors. So, this solution is only method.
+1 it should be noted that copy does not panic if the string is longer or shorter than the sized byte array. hence, no error checking needed in production.
|
8

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)
}

5 Comments

I require byte array to do network packet transfer, save my data into file.
If you want to do that, you should also use a fixed sized int (int32, int64).
This should be the best answer.
@JayD3e This is not correct answer, because I require FIXED bytes array instead of a byte slice.
This doesn't really answer the question; sometimes fixed length arrays are necessary. Once again I will have to search for my answer elsewhere.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.