douba6365 2016-04-04 02:39 采纳率: 100%
浏览 179
已采纳

为什么审核报告uint(0)可能太小而不能转换63?

The Go Programming Language book, exercise 6.5, the author told us using this expression:

32 << (^uint(0) >> 63)

to check whether the platform is 32-bit or 64-bit.

The expression is quite clear, and we can check the result with a simple code:

package main

import "fmt"

func main() {
    fmt.Println(32 << (^uint(0) >> 63))
}

The code print 0 on 32-bit platform and 64 on 64-bit platform.

However, using go vet with the file, I receive the warning:

$ go vet ex6-5.go 
ex6-5.go:6: ^uint(0) might be too small for shift of 63
exit status 1

Why does go vet show me that warnings? How can I prevent it?

  • 写回答

2条回答 默认 最新

  • douluo3256 2016-04-04 02:54
    关注

    This is because uint is not a fixed bitwise length type, it could be as short as a 32 bits, so not sufficient for you to right shift by 63.

    This is also the reason why you could use this expression to test the platform, since uint would take the most efficient int type on the platform.

    If on 32-bit platform, uint is 32-bit length, and thus the right shift would give 0, which causes 32 in the end as the result of 32 << 0. But on 64-bit platform, uint gives 64-bit, and thus right shift 63 bits would give you 1 instead of 0, which results in 64 at the end since 32 << 1 gives 64.

    Take a look at the source code of vet:

    71      case types.Int, types.Uint, types.Uintptr:
    72          // These types may be as small as 32 bits, but no smaller.
    73          size = 32
    74          msg = "might be "
    ...
    78      if amt >= size {
    79          ident := f.gofmt(x)
    80          f.Badf(node.Pos(), "%s %stoo small for shift of %d", ident, msg, amt)
    81      }
    

    That is to say, as long as you are using uint and right shift by 63 bits, with go vet checking shift, there's no way to escape the check. You could try to skip that by providing the flag to check:

    go tool vet -shift=false yourfile.go
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?