给定一个构造体如下所示,能够采纳不同的办法来定义一个构造体切片。
// 申明 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}]