位移位 << 和乘法 * 优先级

Bitshift << and multiplication * precedence

试过这个代码 on Go playground:

package main

import (
    "fmt"
)

func main() {
    log2Dim := uint32(9)
    
    SIZE := 1 << 3 * log2Dim
    fmt.Printf("Result: %v\n", SIZE)
    
    SIZE = 1 << (3 * log2Dim)            // => only difference: adding ( )
    fmt.Printf("Result: %v\n", SIZE)
}

这是打印出来的:

Result: 72
Result: 134217728

为什么仅将 ( ) 添加到包含 <<* 操作的语句中会产生巨大差异?

根据this*的优先级高于<<,这是Google第一个搜索bitshift precedence golang[=28]的结果=].

您链接的页面有误。 Go 只有一个规范,而且很清楚 operator precedence:

There are five precedence levels for binary operators. Multiplication operators bind strongest, followed by addition operators, comparison operators, && (logical AND), and finally || (logical OR):

    5             *  /  %  <<  >>  &  &^
    4             +  -  |  ^
    3             ==  !=  <  <=  >  >=
    2             &&
    1             ||

Binary operators of the same precedence associate from left to right. For instance, x / y * z is the same as (x / y) * z.

乘法和位移位处于相同的优先级,因此应用“从左到右”规则,使您的代码等同于 (1 << 3) * log2Dim

注意从左到右表示在代码中,而不是在优先级table。这可以从规范中给出的示例中看出。

二元运算符有五个优先级。 *<<的优先级相同:5。相同优先级的二元运算符从左到右关联,所以1 << 3 * log2Dim等价于(1 << 3) * log2Dim.

来源:https://golang.org/ref/spec#Operators