Golang 中的管道字符

Pipe character in Golang

golang.org/x/sys/windows/svc 中有一个包含此代码的示例:

const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue

竖线 | 字符是什么意思?

The Go Programming Language Specification

Arithmetic operators

|    bitwise OR             integers

Go 编程语言在 The Go Programming Language Specification 中定义。

这里的|不是管道字符,而是字符,位操作之一。

例如1 | 1 = 1,1 | 2 = 3,0 | 0 = 0.

正如其他人所说,它是按位 [inclusive] OR 运算符。更具体地说,运算符用于创建位掩码标志,这是一种基于按位算术组合选项常量的方法。例如,如果您的选项常量是 2 的幂,如下所示:

const (
    red = 1 << iota    // 1 (binary: 001) (2 to the power of 0)
    green              // 2 (binary: 010) (2 to the power of 1)
    blue               // 4 (binary: 100) (2 to the power of 2)
)

然后你可以像这样将它们与按位或运算符组合起来:

const (
    yellow = red | green          // 3 (binary: 011) (1 + 2)
    purple = red | blue           // 5 (binary: 101) (1 + 4)
    white = red | green | blue    // 7 (binary: 111) (1 + 2 + 4)
)

所以它只是提供了一种基于位运算组合选项常量的方法,依赖于二的幂在二进制数系统中的表示方式;注意使用 OR 运算符时二进制位是如何组合的。 (有关更多信息,请参阅 C 编程语言中的 this example。)因此,通过组合示例中的选项,您只是允许服务接受停止、关闭 暂停并继续命令。