zoukankan      html  css  js  c++  java
  • 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  
  • 相关阅读:
    Codeforces Round #296 (Div. 2B. Error Correct System
    实验十二 图的建立与遍历
    1561: (More) Multiplication
    1562: Fun House
    hdu 2203 亲和串
    hdu 3549Flow Problem
    poj 2182 Lost Cows
    poj 3468A Simple Problem with Integers
    hdu1698 Just a Hook
    栈和队列的面试题Java实现
  • 原文地址:https://www.cnblogs.com/fanbi/p/10082521.html
Copyright © 2011-2022 走看看