go语言数值常量的疑惑

老青蛙嘎嘎嘎 2014-05-12 05:06:55
http://tour.golang.org/ 中的 “Numeric Constants” 说:“An untyped constant takes the type needed by its context.” ,到底是什么意思? 常量的类型在声明时确定还是在调用常量时,类型才确定?具体调试例子如下:

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))
fmt.Printf(“%T\n", Small)
}

运行此代码,程序输出显示 Small 为 int 类型,但是 needFloat 函数的输入为 float64 类型,int 类型可以直接赋值给 float64 类型么? go 语言不同类型的值互相赋值时,语言规范要求必须显示转换,但此处并没有显示转换!难道 Small 的类型会变化,在 needInt(Small) 和 fmt.Printf(“%T\n", Small) 中,Small 为 int 类型,在 needFloat(Small) 中,Small 为 float64 类型?
另一个问题,Big 的类型如何打印出来? fmt.Printf(“%T\n", Big) 无法打印,提示 ”constant 1267650600228229401496703205376 overflows int“
...全文
160 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
飃颻 2014-05-13
  • 打赏
  • 举报
回复
如果不显式指定常量的数值类型, Go语言将根据环境自行判断和指定, 可以作为int,也可以作为float64。
老青蛙嘎嘎嘎 2014-05-13
  • 打赏
  • 举报
回复
Small 在两个大地方具有两种类型,好像不是在编译器确定的,难以理解啊
老青蛙嘎嘎嘎 2014-05-13
  • 打赏
  • 举报
回复
未指定类型的常量由上下文来确定其类型
十一文 2014-05-12
  • 打赏
  • 举报
回复
Big = 1 << 100 Small = Big >> 99 big 为float64 吧 常量类型 是编译期确定其类型的

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧