2016-10-16 17 views
1

尋找golang's 2D slices和無法理解在最後一個例子中使用的語法:這個「常用成語」究竟是如何運作的?在文檔

func main() { 
    XSize := 5 
    YSize := 5 

    // Allocate the top-level slice, the same as before. 
    picture := make([][]uint8, YSize) // One row per unit of y. 

    // Allocate one large slice to hold all the pixels. 
    pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8. 

    // Loop over the rows, slicing each row from the front of the remaining pixe ls slice. 
    for i := range picture { 
     picture[i], pixels = pixels[:XSize], pixels[XSize:] 
    } 
} 

我發現如果這被添加到文檔和變化筆者有這個正常/易於理解的代碼change request

// Loop over the rows, slicing each row. 
for i := range picture { 
    picture[i] = pixels[i*XSize:(i+1)*XSize] 

然而,有這樣的評論:

罰款。另一種常見的成語是爲了避免數學:

picture[i], pixels = pixels[:XSize], pixels[XSize:]

我的問題是如何在上述實現同爲「避免數學」方法?一些關於發生的事情的文檔將會很棒。

回答

5

此:

picture[i], pixels = pixels[:XSize], pixels[XSize:] 

是一個元組assignment。它爲picture[i]賦值,併爲pixels賦值。按順序分配的值是pixels[:XSize]pixels[XSize:]

該作業分兩個階段進行。首先,左邊的index expressionspointer indirections(包括selectors中的隱式指針間接)的操作數和右邊的表達式都是evaluated in the usual order。其次,作業按照從左到右的順序進行。

這裏發生的是,當在循環開始(i = 0),picture(第一行)的第一個元素被分配與切片值是所述第一XSize元件pixels,並且pixels切片resliced所以其第一個元素將是XSizeth元素+1。

所以在下一迭代picture[i]將是picture(第2行)的第二元件,同樣,從pixels第一XSize元件將被設置爲它作爲一個切片。但是由於在前一次迭代中我們解決了pixels,在每次迭代中它的第一個XSize元素將成爲後續行。

+0

敬畏的權利。完全合理。'(picture [i],pixels)=(pixels [:XSize],pixels [XSize:])'。只是沒有看到這種方式。 – Jonathan

2

這個元組分配的例子可以寫成這樣:

for i := range picture { 
    picture[i]= pixels[:XSize] 
    pixels = pixels[XSize:] 
} 

現在可以更輕鬆地看到,圖片這是第一XSIZE項目像素

像素在每個循環被修改並丟棄其第一XSIZE項目。