dpp34603
2015-06-29 10:25
浏览 1.3k
已采纳

Golang在字符串切片中追加字符串

How to append string in a string sclice? I tried

s := make([]string, 1, 4)
s[0] = "filename"
s[0] := append(s[0], "dd")

But it is not correct. Then I tried

s[:1] := append(s[:1], "dd")

But it is not correct either.

How can I append a string to s[0]?

图片转代码服务由CSDN问答提供 功能建议

如何在字符串切片中附加字符串? 我尝试过

 <  code> s:= make([] string,1,4)
s [0] =“文件名” 
s [0]:= append(s [0],“ dd”)
   
 
 

,但这是不正确的。 然后我尝试了

  s [:1]:= append(s [:1],“ dd”)
   
 
  

但这也不正确。

如何将字符串附加到 s [0]

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doumo1807831 2015-06-29 10:31
    已采纳

    The builtin append() function is for appending elements to a slice. If you want to append a string to a string, simply use the concatenation +. And if you want to store the result at the 0th index, simply assign the result to it:

    s[0] = s[0] + "dd"
    

    Or short:

    s[0] += "dd"
    

    Note also that you don't have to (can't) use := which is a short variable declaration, since your s slice already exists.

    fmt.Println(s) output:

    [filenamedd]
    

    If you want to append to the slice and not to the first element, then write:

    s = append(s, "dd")
    

    fmt.Println(s) output (continuing the previous example):

    [filenamedd dd]
    

    Try these on the Go Playground.

    点赞 评论

相关推荐 更多相似问题