Golang掘削の旅-定数変換問題

3627 ワード

Golang掘削の旅-定数変換問題
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.エラー分析
まずエラー解析を行い,直感的にはbyte123123という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を表すことができ、ここでの定数123123byteタイプと直接表すことができないため、問題が発生している.変数のタイプ変換:
A non-constant value x can be converted to type T in any of these cases:
  • ** x is assignable to T . **//主な原因
  • ignoring struct tags (see below), x 's type and T have identical underlying types.
  • ignoring struct tags (see below), 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の初心者として、分からないなら覚えておきます.