我<<在Golang中使用shift运算符面临一个奇怪的问题.在我的最终代码中,移位值将是两个整数的绝对值.但是,Go包只定义了值的Abs函数float64,所以我需要转换参数来使用它,然后将结果转换回来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)))
Run Code Online (Sandbox Code Playgroud)
我收到的错误是:
invalid operation: 1 << uint(math.Abs(10)) (shift of type float64)
Run Code Online (Sandbox Code Playgroud)
但是,似乎只有施法操作才有效:
var test = uint(math.Abs(10))
fmt.Println(reflect.Kind(test))
// uint32
Run Code Online (Sandbox Code Playgroud)
这是一个Golang问题吗?我没有在规格中找到的行为?我根本不懂的正常行为?
这是一个游乐场:http://play.golang.org/p/36a8r8CCYL