Technology Engineering

178inaba の技術ブログ

go-cmpでuintが16進数で表示される問題を解決した

一ヶ月くらい前だがgo-cmpuint が16進数で表示される問題を解決した。

go-cmpは差分がいい感じに表示されるので重宝していたのだがuint系の変数だけ16進数で表示されるのが気になっていた。

https://play.golang.org/p/uE2CalqpkTZ

  main.Ints{
-   Int:    0,
+   Int:    255,
-   Uint:   0x00,
+   Uint:   0xff,
-   Uint8:  0x00,
+   Uint8:  0xff,
-   Uint16: 0x00,
+   Uint16: 0xff,
-   Uint32: 0x00,
+   Uint32: 0xff,
-   Uint64: 0x00,
+   Uint64: 0xff,
  }

同僚も気にしていて需要がありそうだと思ったのでプルリクを出してみた。

github.com

プルリクがマージされて v0.4.1 以上でuint系の変数が10進数で表示されるようになったので同じく気になってた方はぜひバージョンアップしてみてください。

https://play.golang.org/p/dGhSMmjFVnS

  main.Ints{
-   Int:    0,
+   Int:    255,
-   Uint:   0,
+   Uint:   255,
-   Uint8:  0,
+   Uint8:  255,
-   Uint16: 0,
+   Uint16: 255,
-   Uint32: 0,
+   Uint32: 255,
-   Uint64: 0,
+   Uint64: 255,
  }

ちなみに uint8 のスライスだけは10進数になりません。

https://play.golang.org/p/Osxp1JT_Huc

  main.Ints{
    Int: []int{
-       0, 0,
+       255, 255,
    },
    Uint: []uint{
-       0, 0,
+       255, 255,
    },
    Uint8: []uint8{
-       0x00, 0x00, // -|..|
+       0xff, 0xff, // +|..|
    },
    Uint16: []uint16{
-       0, 0,
+       255, 255,
    },
    Uint32: []uint32{
-       0, 0,
+       255, 255,
    },
    Uint64: []uint64{
-       0, 0,
+       255, 255,
    },
  }

これは byteuint8 の型エイリアスであり、go-cmpが設計思想を「byte スライスは16進数で表示すべき」としているためです。

https://golang.org/pkg/builtin/#byte