翻译进度
2
分块数量
1
参与人数

Conversions

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


转换将一个表达式的类型转换为了所需要的特定类型。转换可能是写出的强制类型转换,也可能由表达式上下文推断。

一个 显示的 转换是由类似于 T(x) 形式的表达式实现的,其中 T 是要转换为的类型而 x 则是要转换为 T 类型的变量。

Conversion = Type "(" Expression [ "," ] ")" .

如果类型以操作符*<-开头,或者类型以关键字func开头且没有结果类型列表,则必须在将类型前后添加括号以避免歧义:

*Point(p)        // same as *(Point(p))
(*Point)(p)      // p is converted to *Point

一个 常量 值 x 可以被转换为 T 的条件是 x 可以 表示为 类型T。 作为一种特殊情况,一个整数常量 x 可以被显示转换为 字符串类型 的条件与非常量类型的转换规则相同。 

转换常量会产生一个有类型的常量。

singee 翻译于 4年前
uint(iota)               // iota value of type uint
float32(2.718281828)     // 2.718281828 of type float32
complex128(1)            // 1.0 + 0.0i of type complex128
float32(0.49999999)      // 0.5 of type float32
float64(-1e-1000)        // 0.0 of type float64
string('x')              // "x" of type string
string(0x266c)           // "♬" of type string
MyString("foo" + "bar")  // "foobar" of type MyString
string([]byte{'a'})      // not a constant: []byte{'a'} is not a constant
(*int)(nil)              // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
int(1.2)                 // illegal: 1.2 cannot be represented as an int
string(65.0)             // illegal: 65.0 is not an integer constant

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.

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~