dsa5233
2017-09-22 11:22
浏览 58
已采纳

在Go中,如何复制切片的最后一个元素?

If I have a Python list, it is simple to duplicate the last element: l.append(l[-1]). Is there an elegant way to do this with Go slices?

The best I have so far is data = append(data, data[len(data) - 1]).

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

如果我有Python列表,可以很容易地复制最后一个元素: l.append(l [-1])

到目前为止,我最好的方法是 data = append(data,data [len(data)-1])< /code>。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • dsiy62758 2017-09-22 11:41
    最佳回答

    That is the proper way to do it.

    In Go you can't use negative indices, so the index of the last element is len(data) -1.

    And in Go append() is a builtin function and not a method of slices, and it returns a new slice value which you have to assign or store if you need the extended slice, so there's nothing you can make shorter in your code in general.

    Note that if you were on to create your own type, you could attach methods to it which could simpify things. For example:

    type ints []int
    
    func (i *ints) append(es ...int) {
        *i = append(*i, es...)
    }
    
    func (i *ints) appendLast() {
        *i = append(*i, (*i)[len(*i)-1])
    }
    

    Using it:

    is := ints{1, 2, 3}
    fmt.Println(is)
    
    is.append(4, 5) // Append some elements
    fmt.Println(is)
    
    is.append(is[len(is)-1]) // Append last element explicitly
    fmt.Println(is)
    
    is.appendLast() // Append last element using appendLast method
    fmt.Println(is)
    
    // You can also use it for []int values, with conversion:
    is2 := []int{1, 2, 3}
    (*ints)(&is2).appendLast()
    fmt.Println(is2)
    

    Output (try it on the Go Playground):

    [1 2 3]
    [1 2 3 4 5]
    [1 2 3 4 5 5]
    [1 2 3 4 5 5 5]
    [1 2 3 3]
    

    You can also use simple util functions without creating a new type:

    func appendLast(i []int) []int {
        return append(i, i[len(i)-1])
    }
    
    func appendLast2(i *[]int) {
        *i = append(*i, (*i)[len(*i)-1])
    }
    
    func main() {
        is := []int{1, 2, 3}
        fmt.Println(is)
    
        is = appendLast(is)
        fmt.Println(is)
    
        appendLast2(&is)
        fmt.Println(is)
    }
    

    Output (try it on the Go Playground):

    [1 2 3]
    [1 2 3 3]
    [1 2 3 3 3]
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题