2015-10-04 64 views
0

我讀的排序中去實施,並有在func Sort(data Interface)實施這個特別的循環:>> =運算符在golang中做了什麼?

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

排序實現:https://golang.org/src/sort/sort.go

有人能向我解釋什麼是>> =運營商呢?

編輯:這只不過是一個變形,然後是一個虛構。我認爲它在一個循環中的事實縈繞在我的腦海裏。

+2

'I >> = 1' ='I = i >> 1' – Dave

+2

[Go << and >> operators]可能重複(http://stackoverflow.com/questions/5801008/go-and-operators) –

回答

2

>>運算符是向右移位運算符。

>>=是右移轉讓的合同表。

i >>= 1 

這是同樣的

tmp := i >> 1 
i = tmp 

這是同樣的事情(沒有需求創造一個新的變量)

i := i >> 1 
4

檢查: https://golang.org/ref/spec

left shift    integer << unsigned integer 

right shift   integer >> unsigned integer 

移位運算由右操作數指定的移位計數 移位左操作數。如果 左邊的操作數是一個有符號的整數,並且它是一個 無符號整數,則它們實現算術移位。換班次數沒有上限。位移 的行爲就好像左操作數被n次移位n次,移位爲 的次數爲n。因此,與x * 2相同並且x >> 1是與x/2相同但是截斷爲負無窮大的 。

類似的問題:

Go <<and>> operators

double less operator in Go Tour 37