I am trying to benchmark some Decoding code. I have printed the encoding byte array, so I can hardcode it in the test file, to separate out the Encode part.
Therefore I have fmt.Println() a byte array
buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(<my struct>)
if err != nil {
log.Fatal(err)
}
byteQuads := buf.Bytes()
buf.Reset()
fmt.Println(byteQuads) // << [77 255 129 3 1 1 7 82...]
// or
fmt.Println(string(byteQuads[:])) // << M��...
Question: How can read this hardcode into a byte array([]byte) again
b := []byte(???) // [77 255 129 3 1 1 7 82...] or M��
gob.NewDecoder(bytes.NewReader(b))
CodePudding user response:
Would this help? I'm assuming the bytesQuad can be read from your file.
type MyStruct struct {
Value int
}
func main() {
buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(MyStruct{Value: 3})
if err != nil {
log.Fatal(err)
}
byteQuads := buf.Bytes()
buf.Reset()
fmt.Println(byteQuads) // << [77 255 129 3 1 1 7 82...]
// or
fmt.Println(string(byteQuads[:])) // << M��...
// deserialize
var myStruct MyStruct
reader := bytes.NewReader(byteQuads)
dec := gob.NewDecoder(reader)
err = dec.Decode(&myStruct)
if err != nil {
log.Fatal(err)
}
fmt.Println(myStruct.Value)
}
CodePudding user response:
You can use constructor syntax with slices. Lets show an example:
array := []int{1, 2, 3}
Equivalent in python is:
array = [1, 2, 3]
