go - 将 float 分配给struct的整数元素

标签 go constants

我正在进行“围棋之旅”,我对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...



以下可分配性规则涵盖了上述分配:


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/

相关文章:

Golang - Github Mux, context.go -> 没有这样的文件或目录

oop - 如何在golang中创建一个自动调用的结构方法?

angular - 使用一些配置文件在 Angular 5 中完全外部常量

c++ - 数组初始化在 C++ 中使用 const 变量

c++ - 将 double 分配给 const int& vs int 分配给 const int&

c++ - 如何声明模板常量类型?

types - 类型断言后的 golang 类型转换

http - golang从套接字解析分块的HTTP响应-逐 block 读取

go - 如何使用 go 1.5+ 创建静态链接的 golang 可执行文件

java - 在 Java 项目中查找重复常量