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

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]?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办