0
0

More than 3 years have passed since last update.

【Go】「binary.Write: invalid type 」が発生してバイナリ書き込みができない

Posted at

問題

以下のような構造体をバッファに書き込もうとしてエラーが発生した。

main.go
type T1 struct {
    A int8
    B int8
}

type T2 struct {
    T1
    C string
    D int8
}
var (
    t1 T1
    t2 T2
)

t2.T1 = t1
t2.C  = "hoge"
t2.D  = 1234

buf := new(bytes.Buffer)

// ここで該当のエラーが発生
//
// binary.Write: invalid type *main.T2
err := binary.Write(buf, binary.LittleEndian, &t2)


原因

埋め込みがまずいと予想していたが、どうやらstringを書きこもうとして出力されるエラーだとわかった。

ドキュメントによると、1

Write は data のバイナリ表現を w に書き込みます。 data は,固定サイズ値または固定サイズ値のスライス,あるいはそのようなデータへのポインタでなければなりません。

対処法

なので、string固定長byteに変換して、構造体へコピーすれば良さそう

The Go Playground

main.go
type T1 struct {
    A int8
    B int8
}

type T2 struct {
    T1
    C [10]byte
    D int8
}


var (
    t2 T2 // 書き込み用
    r2 T2 // 読み込み用
)

// 固定長byteにコピー
copy(t2.C[:], "hoge")

buf := new(bytes.Buffer)

// バッファに書き込み
err := binary.Write(buf, binary.LittleEndian, &t2)

// バッファから読み込み
err = binary.Read(buf, binary.LittleEndian, &r2)

// 固定長byteをstringに変換
fmt.Println(string(r2.C[:]))

参考


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0