5

I was reading the implementation of sort in go, and there is this particular loop in the implementation of func Sort(data Interface):

for i := n; i > 0; i >>= 1 {
    maxDepth++
}

Sort implementation : https://golang.org/src/sort/sort.go

Can someone explain to me what does the >>= operator do ?

Edit: It's simply a shift followed by an affectation. I think the fact it was in a loop bugged my mind.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
HenriTel
  • 184
  • 10

2 Answers2

5

The >> operator is the right shift operator.

>>= is a contracted form of the right shift operator and assignment:

i >>= 1

It is the same as:

tmp := i >> 1
i = tmp

And that is the same thing as (without the need to create a new variable):

i := i >> 1
nessuno
  • 26,493
  • 5
  • 83
  • 74
4

Check: https://golang.org/ref/spec

left shift             integer << unsigned integer

right shift            integer >> unsigned integer

The shift operators shift the left operand by the shift count specified by the right operand. They implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer. There is no upper limit on the shift count. Shifts behave as if the left operand is shifted n times by 1 for a shift count of n. As a result, x << 1 is the same as x*2 and x >> 1 is the same as x/2 but truncated towards negative infinity.

Similar questions:

Go << and >> operators

double less operator in Go Tour 37

Community
  • 1
  • 1
Pawel Gumiela
  • 1,992
  • 2
  • 20
  • 36