Golang掘削の旅-定数変換問題
Golang掘削の旅-定数変換問題
0.問題の説明
次のコードを参照してください.
コードの目的は
では、問題は、なぜ同じ機能、2つの実装、なぜ定数操作の
1.エラー分析
まずエラー解析を行い,直感的には
公式サイトの定数の説明に従って:
Numeric constants represent exact values of arbitrary precision and do not overflow.
定数はオーバーフローしないことがわかりましたが、これは浅い原因で、さらなる資料を調べることで、公式サイトのタイプ変換部分では、次のように説明されています.
A constant value
定数は変換可能であり、変換タイプ
A non-constant value ** ignoring struct tags (see below), ignoring struct tags (see below),
変数変換は過去に値を付与できればよいが,
2.問題解決または の生産量を制御する.または を変数で担持する
3.まとめ
これは比較的小さな問題で、
0.問題の説明
次のコードを参照してください.
package main
import (
"fmt"
)
// , byte 123123
func main() {
var x = 123123
fmt.Printf("%b
", byte(x))
fmt.Printf("%b
", byte(123123))
}
コードの目的は
123123
に対してbyte
を用いて遮断することであるが、上記のコードを実行することにより、10行目にエラーが報告され、エラー情報はconstant 480 overflows byte
であることがわかる.注記10
行目により、コードは正常に動作します.では、問題は、なぜ同じ機能、2つの実装、なぜ定数操作の
10
行目で実行できないのかということです.1.エラー分析
まずエラー解析を行い,直感的には
byte
が123123
というint
型の定数を強制型変換できない場合にオーバーフロー問題が発生したが,int
変数x
を同型操作した場合には問題が発生しなかったため,問題は定数の型変換にあった.公式サイトの定数の説明に従って:
Numeric constants represent exact values of arbitrary precision and do not overflow.
定数はオーバーフローしないことがわかりましたが、これは浅い原因で、さらなる資料を調べることで、公式サイトのタイプ変換部分では、次のように説明されています.
A constant value
x
can be converted to type T
if x
is representable by a value of T
. 定数は変換可能であり、変換タイプ
T
に限定してx
を表すことができ、ここでの定数123123
はbyte
タイプと直接表すことができないため、問題が発生している.変数のタイプ変換:A non-constant value
x
can be converted to type T
in any of these cases: x
is assignable to T
. **//主な原因x
's type and T
have identical underlying types. x
's type and T
are pointer types that are not defined types, and their pointer base types have identical underlying types. x
's type and T
are both integer or floating point types. x
's type and T
are both complex types. x
is an integer or a slice of bytes or runes and T
is a string type. x
is a string and T
is a slice of bytes or runes. 変数変換は過去に値を付与できればよいが,
int
型の変数は遮断操作によりbyte
型に値を付与できるので問題ない.2.問題解決
byte
の許容範囲内、例えば123
の3.まとめ
これは比較的小さな問題で、
golang
の初心者として、分からないなら覚えておきます.