droxlzcgnr639823 2017-06-19 23:59
浏览 51
已采纳

可以向切片添加append方法

I have something like the following type structure below:

type Set []*Element

func (set *Set) AppendElements(elements []*Elements) {
    // ?
}

Obviously simply appending elements to a slice is not very useful. However, the actual function takes some value, does some business logic, and then appends the elements. However, I am facing the difficulty that modifications to the slice inside of the method to not actually change the value of the slice to outside callers, because the append method allocates a new slice that is not seen by the callers.

Is there a way to append to the slice in a method or should the slice be wrapped in a struct or something else?

package main

import "fmt"

type Element int
type Set []*Element

func (ptr *Set) AppendElements(elements []*Element) {
    set := *ptr
    set = append(set, elements...)
}

func main() {
    i := Element(1)
    var set Set
    set.AppendElements([]*Element{&i})

    for _, el := range set {
        fmt.Println(el)
    }
}

More specifically, the above prints nothing.

  • 写回答

1条回答 默认 最新

  • duancheng3342 2017-06-20 00:32
    关注

    You're modifying the slice, but you never assign it back to the pointer.

    func (ptr *Set) AppendElements(elements []*Element) {
        set := *ptr
        set = append(set, elements...)
        *ptr = set
    }
    

    Usually though, one would dereference the pointer directly in the append statement:

    func (set *Set) AppendElements(elements []*Element) {
        *set = append(*set, elements...)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持