【发布时间】:2014-07-21 12:40:43
【问题描述】:
我在 Golang 中使用移位运算符 << 时遇到了一个奇怪的问题。在我的最终代码中,移位值将是两个整数的绝对值。但是,Go 包只为 float64 值定义了 Abs 函数,所以我需要转换参数才能使用它,然后将结果转换回 uint。
最后,这个值将用作float64 参数,所以之后我将它转换回float64。
问题是返回值的转换似乎没有像我预期的那样工作......
var test float64
// all the following lines are working as expected
test = float64(1 << 10)
test = float64(1 << uint(10))
test = float64(1 << uint(float64(11-1)))
test = float64(1 << uint(-float64(1-11)))
// but this one does not: error at compilation
test = float64(1 << uint(math.Abs(10)))
我收到的错误是:
invalid operation: 1 << uint(math.Abs(10)) (shift of type float64)
但是,似乎单独的 cast 操作有效:
var test = uint(math.Abs(10))
fmt.Println(reflect.Kind(test))
// uint32
这是一个 Golang 问题吗?我在规范中没有找到的行为?我根本不明白的正常行为?
【问题讨论】: