unexpected slice append behaviour

前端 未结 3 1871
臣服心动
臣服心动 2021-02-06 12:58

I encountered weird behaviour in go code today: when I append elements to slice in loop and then try to create new slices based on the res

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 13:13

    There is also a little bit simpler way to implement copyAndAppend function:

    func copyAndAppend(source []string, items ...string) []string {
        l := len(source)
        return append(source[:l:l], items...)
    }
    

    Here we just make sure that source has no available capacity and so copying is forced.

提交回复
热议问题