Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe character in Golang

In the package golang.org/x/sys/windows/svc there is an example that contains this code:

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

What does the pipe | character mean?

like image 582
Pierre Prinetti Avatar asked Mar 14 '16 12:03

Pierre Prinetti


2 Answers

As others have said, it's the bitwise [inclusive] OR operator. More specifically, the operators are being used to create bit mask flags, which is a way of combining option constants based on bitwise arithmetic. For example, if you have option constants that are powers of two, like so:

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

Then you can combine them with the bitwise OR operator like so:

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

So it simply provides a way for you to combine option constants based on bitwise arithmetic, relying on the way that powers of two are represented in the binary number system; notice how the binary bits are combined when using the OR operator. (For more information, see this example in the C programming language.) So by combining the options in your example, you are simply allowing the service to accept stop, shutdown and pause and continue commands.

like image 116
user162097 Avatar answered Sep 21 '22 04:09

user162097


The Go Programming Language Specification

Arithmetic operators

|    bitwise OR             integers

The Go programming language is defined in The Go Programming Language Specification.

like image 39
peterSO Avatar answered Sep 19 '22 04:09

peterSO