我正在进行“围棋之旅”,我对4/27(https://tour.golang.org/moretypes/4)感到困惑
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9 // <- this line does not produce a type error
fmt.Println(v) // {1000000000 2} implicite conversion of int to float?
}
我希望使用JavaScript而不是强类型语言。我一定缺少基本的东西。
最佳答案
这行:
p.X = 1e9
是assignment。规范对分配有以下要求:
In assignments, each value must be assignable to the type of the operand to which it is assigned...
以下可分配性规则涵盖了上述分配:
x
is an untyped constant representable by a value of typeT
.
1e9
是未类型化的floating point constant,并且该值完全可以由int
类型的值表示,因此一切都很好。如果它是一个类型化的常量,例如它将是一个编译时错误。
p.X = float64(1e9)
// error: cannot use float64(1e+09) (type float64) as type int in assignment
因为上述可分配性规则将不适用,所有其他规则均将不适用。
如果未类型化的浮点常量值不能由
int
类型的值表示,则情况相同,例如在以下情况下:p.X = 1e99
// error: constant overflows int
p.X = 1.1
// error: constant 1.1 truncated to integer
关于go - 将 float 分配给struct的整数元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59705224/