The nature of the pipe in the Golang

The golang.org/x/sys/windows/svc package has an example that contains this code:

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

What does the pipe symbol mean | ?

+5
source share
3 answers

As others have said, this is a bitwise operator [inclusive] OR. More specifically, operators are used to create bitmask flags, which is a way of combining optional constants based on bitwise arithmetic. For example, if you have parameter constants that have two degrees, for example:

 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) ) 

You can then combine them with the bitwise OR operator as follows:

 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) ) 

Thus, it just gives you the ability to combine constant constants based on bitwise arithmetic, relying on how the two functions are represented in a binary number system; note how binary bits are combined when using the OR operator. (For more information, see this example in the C programming language.) Thus, by combining the parameters in your example, you simply allow the service to accept stops, shutdowns, and pauses and continues.

+19
source

Go programming language specification

Arithmetic operators

 | bitwise OR integers 

The Go programming language is defined in the Go programming language specification .

+4
source

| here is not a channel symbol, but a symbol or , one of the bitwise manipulations.

For example, 1 | 1 = 1 1 | 1 = 1 , 1 | 2 = 3 1 | 2 = 3 , 0 | 0 = 0 0 | 0 = 0 .

+1
source

Source: https://habr.com/ru/post/1245017/


All Articles