JSゆるふわめも

がっこうでべんきょうしたことをめもがきしてます

constant xxx truncated to integerについて

Goにおける定数(constant)は定義がかなり緩い型になっており、 それを含んだ式や代入を行う場合明示的に型を指定する必要がある。

stackoverflow.com

上記質問で触れられているリンクを雑&かなり適当な意訳してみた

Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.

型の異なる数値型が一つの式や代入内に現れる場合、型変換が要求される。例えば、int32とint型はとあるアーキテクチャーでは同じサイズを持つかもしれないが、同じ型ではない。

Why does Go not provide implicit numeric conversions? The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes. When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes? It also complicates the compiler; “the usual arithmetic conversions” are not easy to implement and inconsistent across architectures. For reasons of portability, we decided to make things clear and straightforward at the cost of some explicit conversions in the code. The definition of constants in Go—arbitrary precision values free of signedness and size annotations—ameliorates matters considerably, though.

A related detail is that, unlike in C, int and int64 are distinct types even if int is a 64-bit type. The int type is generic; if you care about how many bits an integer holds, Go encourages you to be explicit.

A blog post titled Constants explores this topic in more detail.

何故Goは暗黙的に数値変換を行ってくれないのか C言語のように異なる数値型を意識することなく変換することは便利ですが、それ以上に混乱をもたらします。 符号なしの型を用いた場合はどうなるでしょう?値がものすごく大きな値だったら?その値はオーバーフローするの?結果は動作するアーキテクチャに依存するのでしょうか?これらの問題はコンパイラーにとっても問題です。「一般的」な数値型変換を実装するのは容易ではありませんし、アーキテクチャ依存です。我々は移植性の観点から問題を明確化することにし、素直にコード中で明示的な変換を行うことにしました。ですから、Go言語における定数の定義は任意の精度を持つ値で、それは符号あり、なし・サイズなどを定義しておらず、問題をかなりわかりやすくしています。

このことに関して詳しく言うと、Cと違って、intとint64はたとえそれらが同じビットサイズを持っていても全く違う型とみなされます。int型は汎用型であり、アーキテクチャ依存です。もしintegerのbitサイズが重要ならば、Go言語では明示的な型を使用するべきでしょう。

ブログ記事Constantsではこのトピックについてさらに詳細に説明しています。