给定一个结构体如下所示,可以采用不同的方法来定义一个结构体切片。

// 声明Stock结构体
type Stock struct {
    Name string
    CurrentPrice float64
    LowestPrice float64
    HighestPrice float64
}

方法一:定义时直接赋值

var stocks []Stock = []Stock{
    {
        Name: "工商银行",
        CurrentPrice: 4.80,
        LowestPrice: 4.47,
        HighestPrice: 4.86,
    },
    {
        Name: "农业银行",
        CurrentPrice: 3.03,
        LowestPrice: 2.90,
        HighestPrice: 3.11,
    },
}
[{工商银行 4.8 4.47 4.86} {农业银行 3.03 2.9 3.11}]

方法二:先声明,再使用append逐个添加

    var stocks []Stock
    stock := Stock {
        Name: "工商银行",
        CurrentPrice: 4.80,
        LowestPrice: 4.47,
        HighestPrice: 4.86,
    }
    stocks = append(stocks, stock)
    stock = Stock {
        Name: "农业银行",
        CurrentPrice: 3.03,
        LowestPrice: 2.90,
        HighestPrice: 3.11,
    }
    stocks = append(stocks, stock)
[{工商银行 4.8 4.47 4.86} {农业银行 3.03 2.9 3.11}]

mumingv
24 声望1 粉丝

持之以恒,方得始终