如何在字符串sclice中追加字符串? 我试过了
s := make([]string, 1, 4)
s[0] = "filename"
s[0] := append(s[0], "dd")
但这不正确。然后我试了
s[:1] := append(s[:1], "dd")
但它也不正确。
如何将字符串附加到s[0]
?
答案 0 :(得分:9)
内置append()
函数用于将元素附加到切片。如果您想将string
附加到string
,只需使用串联+
即可。如果要将结果存储在第0个索引处,只需将结果分配给它:
s[0] = s[0] + "dd"
或简短:
s[0] += "dd"
另请注意,由于:=
切片已存在,您不必(不能)s
使用fmt.Println(s)
。
[filenamedd]
输出:
s = append(s, "dd")
如果要附加到切片而不是第一个元素,请写入:
fmt.Println(s)
[filenamedd dd]
输出(继续上一个示例):
"items": [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Espadeiro"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Chardonnay"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
在short variable declaration上尝试这些。