2015-02-14 2 views
4

этот код в builti.goкакой смысл о `... type` в golang

// The append built-in function appends elements to the end of a slice. If 
// it has sufficient capacity, the destination is resliced to accommodate the 
// new elements. If it does not, a new underlying array will be allocated. 
// Append returns the updated slice. It is therefore necessary to store the 
// result of append, often in the variable holding the slice itself: 
// slice = append(slice, elem1, elem2) 
// slice = append(slice, anotherSlice...) 
// As a special case, it is legal to append a string to a byte slice, like this: 
// slice = append([]byte("hello "), "world"...) 
func append(slice []Type, elems ...Type) []Type 

последняя линия заставила меня чувствовать себя очень смущен. Я не знаю значения около ...Type.

это другие коды.

package main 

import "fmt" 

func main() { 
    s := []int{1,2,3,4,5} 
    s1 := s[:2] 
    s2 := s[2:] 
    s3 := append(s1, s2...) 
    fmt.Println(s1, s2, s3) 

}

результат

[1 2] [3 4 5] [1 2 3 4 5] 

Я предполагаю, что функция о ... это выбрать все элементы из elems.

Я не нашел объяснения чиновника

ответ

6

Код в builtin.go служит в качестве документации. Код не скомпилирован.

... указывает, что конечный параметр функции является переменным. Вариадические паремеры - documented in the Go Language specification.

Часть Type является подставкой для любого типа Go.

+0

И вот отличный пост о срезах, которые могут оказаться полезными: https://github.com/golang/go/wiki/SliceTricks –

Смежные вопросы