Go append 省略号

1 前言

Golang append加...用法缘由

2 代码

type Product struct {
	ID    int64   `json:"id"`
	Name  string  `json:"name"`
	Info  string  `json:"info"`
	Price float64 `json:"price"`
}

var products []Product

func initProducts() {
	product1 := Product{ID: 1, Name: "Chicha Morada", Info: "Chicha  level (wiki)", Price: 7.99}
	product2 := Product{ID: 2, Name: "Chicha de jora", Info: "Chicha de sedays (wiki)", Price: 5.95}
	product3 := Product{ID: 3, Name: "Pisco", Info: "Pisco is a emakile (wiki)", Price: 9.95}
	products = append(products, product1, product2, product3)
}

func main() {
	initProducts()
        //如果没有省略号,如下,会提示:
        //Cannot use 'products[i+1:]' (type []Product) as type Product, Inspection info: Reports incompatible types.
        //products = append(products[:i],products[i+1:])

        //正确用法
        products = append(products[:i],products[i+1:]...)
}    

分析:这是append内置方法的定义

// 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  

猜你喜欢

转载自www.cnblogs.com/fanbi/p/10082521.html