可以给切片添加一个append方法吗?

huangapple go评论78阅读模式
英文:

Possible to add an append method to a slice

问题

我有以下类似的类型结构:

type Set []*Element

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

显然,简单地将元素追加到切片中并不是很有用。然而,实际的函数会接收一些值,执行一些业务逻辑,然后追加元素。然而,我面临的困难是,在方法内部对切片进行修改并不会实际改变切片对外部调用者的值,因为append方法会分配一个新的切片,而这个新切片对调用者是不可见的。

有没有一种方法可以在方法中追加到切片中,或者应该将切片包装在结构体中或其他方式?

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)
    }
}

更具体地说,上述代码什么都不会打印出来。

英文:

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

得分: 10

你正在修改切片,但是你没有将其重新分配给指针。

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

通常情况下,可以直接在append语句中取消引用指针:

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

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...)
}

huangapple
  • 本文由 发表于 2017年6月20日 07:59:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/44641663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定