2016-07-27 25 views
0

我嘗試了新的元素添加到切片,就像追加一個新的元素在Python list,但有一個錯誤如何將新元素添加到切片?

package main 

import "fmt" 

func main() { 
    s := []int{2, 3, 5, 7, 11, 13} 
    printSlice(s) 

    s[len(s)] = 100 
    printSlice(s) 
} 

func printSlice(s []int) { 
    fmt.Printf("%v\n", s) 
} 

和輸出

[2 3 5 7 11 13] 

panic: runtime error: index out of range 

哪有然後我在片上添加一個新元素?

在Python中,Go中的slice是closet數據類型到list是否正確?

謝謝。

+2

https://gobyexample.com/slices – abhink

+1

另外在[有效圍棋](https://golang.org/doc /effective_go.html#append),[Go Language Specification](https://golang.org/ref/spec#Appending_and_copying_slices)以及[Go of Tour](https://tour.golang.org/moretypes/) 7) – JimB

+0

另請參閱:http://stackoverflow.com/questions/20195296/golang-append-an-item-to-a-slice/20197469#20197469 – gavv

回答

3

在Go中追加使用內置方法append。例如:

s := []byte{1, 2, 3} 
s = append(s, 4, 5, 6) 
fmt.Println(s) 
// Output: [1 2 3 4 5 6] 

你是正確的,在Go片接近Python的列表,並且,事實上,許多相同的索引和切片操作對他們的工作。

當你這樣做:

s[len(s)] = 100 

它嚇壞了,因爲你不能訪問超出片的長度值。這裏似乎有些混淆,因爲在Python中,它的工作方式完全相同。嘗試上述在Python(除非你已經擴大了名單)會給:

IndexError: list assignment index out of range