为什么float64类型编号在Go中引发与int相关的错误

时间:2019-06-07 02:28:04

标签: go

我正在尝试掌握Golang,在本教程示例之一中,它说An untyped constant takes the type needed by its context.

package main

import "fmt"

const (
    // Create a huge number by shifting a 1 bit left 100 places.
    // In other words, the binary number that is 1 followed by 100 zeroes.
    Big = 1 << 100
    // Shift it right again 99 places, so we end up with 1<<1, or 2.
    Small = Big >> 99
)

func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
    return x * 0.1
}

func main() {
    fmt.Println(needInt(Small))
    fmt.Println(needFloat(Small))

    // Here Big is too large of a number but can be handled as a float64.
    // No compilation error is thrown here.
    fmt.Println(needFloat(Big))

    // The below line throws the following compilation error
    // constant 1267650600228229401496703205376 overflows int
    fmt.Println(Big)
}

在呼叫fmt.Println(Big)时,Golang为什么将Big视作int,而在上下文中应该是float64

我想念什么?

2 个答案:

答案 0 :(得分:4)

fmt.Println的上下文是什么?换句话说,fmt.Println期望Big是什么? interface{}

来自the Go Blog on Constants

  

使用无类型常量调用fmt.Printf时会发生的情况是,创建了一个接口值作为参数传递,并且为该参数存储的具体类型是该常量的默认类型。

因此,常量的默认类型必须为int。该页面继续讨论如何根据语法(不一定是const的值)确定默认值。

答案 1 :(得分:0)

class MyComponent extends Component{ render(){ return <div id="componentId"> ...your child component details here </div> } } 中的

Big的整数类型大于最大int值fmt.Println(Big)

您可以从此逻辑中找到max int

9223372036854775807

2036854775807

要修复此问题,您需要像这样将其强制转换为float64

const MaxUint = ^uint(0)
const MaxInt = int(MaxUint >> 1)
fmt.Println(MaxInt) // print 922337