• 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  
  • 相关阅读:
    Linux 时间同步 03 ntpdate时间同步
    Linux 时间同步 04 ntp时间同步
    Linux 时间同步 02 ntpd、ntpdate的区别
    Linux 时间同步 05 chrony时间同步
    极限编程的12个实践原则
    需要继续理解的
    java的动态代理机制详解
    动态代理详解(一)应用示例
    动态代理详解(二)原理解析
    说说Java代理模式
  • 原文地址:https://www.cnblogs.com/fanbi/p/10082521.html
Copyright © 2020-2023  润新知