DRYな備忘録

Don't Repeat Yourself.

【Go言語】意地でもsliceをswitch-caseで比較したい

invalid case []byte literal in switch (can only compare slice foo to nil)

switch response[:4] {
case []byte{0,0,0,0}, []byte{1,0,0,0}, []byte{2,0,0,0}:
    fmt.Println("do something")
}
// これ動かないやつ

可変長であるsliceはnilとの比較だけが許されているようだ。固定長ならどうか?

やったこと

  1. 固定長arrayをつくる
  2. sliceとしてcopyにかける
  3. 固定長arrayと比較する
var header [4]byte
copy(header[:], response[:4])
switch header {
case [4]byte{0,0,0,0}, [4]byte{1,0,0,0,}, [4]byte{2,0,0,0}:
    fmt.Println("do something")
}

The Go Playground

DRYな備忘録として