A Tour of Go Numeric Constants

Go语言常量与类型转换

Numeric constants are high-precision values.

An untyped constant takes the type needed by its context.

Try printing needInt(Big) too.

 

package main 

import "fmt"

const (
    Big = 1 << 100
    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))
    fmt.Println(needFloat(Big))
}

 

 

 

 

 

package main 

import "fmt"

const (
    Big = 1 << 100
    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(Small);
    var intVariable int = 1
    //var float32Variable float32 = 1.2
    fmt.Println(needInt(Small))
    // constant 1267650600228229401496703205376 overflows int
    //fmt.Println(needInt(Big))
    fmt.Println(needFloat(Small))
    fmt.Println(needFloat(Big))

    //go语言对类型的要求是很严格的,所以你不能传递int到float中或者float到int
    fmt.Println(needInt(intVariable))
    //cannot use float32Variable (type float32) as type int in argument to needInt
    //fmt.Println(needInt(float32Variable))
    //cannot use intVariable (type int) as type float64 in argument to needFloat
    //fmt.Println(needFloat(intVariable))
    //cannot use float32Variable (type float32) as type float64 in argument to needFloat
    //fmt.Println(needFloat(float32Variable))

}

不过常量却相对宽容一些

    //constant 1267650600228229401496703205376 overflows int
    fmt.Println(Big);

 

转载于:https://www.cnblogs.com/ghgyj/p/4052714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值