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  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM