【问题标题】:How to remove an item from a slice by calling a method on the slice如何通过调用切片上的方法从切片中删除项目
【发布时间】:2013-09-05 03:59:13
【问题描述】:

围棋又难倒了我。希望有人可以提供帮助。我创建了一个切片 (mySlice),其中包含指向结构 (myStruct) 的指针。

问题在于“删除”方法。当我们在 "Remove" 里面时一切都很好,但是一旦我们返回,切片大小并没有改变,所以我们看到最后一个元素列出了两次。

我最初尝试使用“添加”方法中使用的相同模式编写“删除”,但它无法编译并且已被注释掉。

我可以通过将新创建的切片返回给调用函数来使其工作,但我不想这样做,因为 mySlice (ms) 是单例。

如果我还没有问够的话......

“添加”方法的代码正在运行,虽然我不确定如何。据我所知,“添加”正在接收指向切片标头(第 3 项“结构”)的指针。根据我的阅读,切片的长度和容量不会传递给方法(当按值传递时),所以也许将指针传递给切片允许方法查看和使用长度和容量,从而允许我们“附加”。如果这是真的,那么为什么相同的模式在“删除”中不起作用?

非常感谢大家的见解和帮助!

package main

import (
    "fmt"
)

type myStruct struct {
    a int
}
type mySlice []*myStruct

func (slc *mySlice) Add(str *myStruct) {
    *slc = append(*slc, str)
}

//does not compile with reason: cannot slice slc (type *mySlice)
//func (slc *mySlice) Remove1(item int) {
//  *slc = append(*slc[:item], *slc[item+1:]...)
//}

func (slc mySlice) Remove(item int) {
    slc = append(slc[:item], slc[item+1:]...)
    fmt.Printf("Inside Remove = %s\n", slc)
}

func main() {
    ms := make(mySlice, 0)
    ms.Add(&myStruct{0})
    ms.Add(&myStruct{1})
    ms.Add(&myStruct{2})
    fmt.Printf("Before Remove:  Len=%d, Cap=%d, Data=%s\n", len(ms), cap(ms), ms)
    ms.Remove(1) //remove element 1 (which also has a value of 1)
    fmt.Printf("After Remove:  Len=%d, Cap=%d, Data=%s\n", len(ms), cap(ms), ms)
}

结果...

Before Remove:  Len=3, Cap=4, Data=[%!s(*main.myStruct=&{0}) %!s(*main.myStruct=&{1}) %!s(*main.myStruct=&{2})]

Inside Remove = [%!s(*main.myStruct=&{0}) %!s(*main.myStruct=&{2})]

After Remove:  Len=3, Cap=4, Data=[%!s(*main.myStruct=&{0}) %!s(*main.myStruct=&{2}) %!s(*main.myStruct=&{2})]

【问题讨论】:

    标签: go slice


    【解决方案1】:

    Remove1() 第一次你是对的。 Remove 获取切片的副本,因此无法更改切片的长度。

    remove 函数中的问题是,根据 Go 中的操作顺序,切片先于解引用。

    解决方法是将*slc = append(*slc[:item], *slc[item+1:]...) 更改为*slc = append((*slc)[:item], (*slc)[item+1:]...)。

    但是,为了可读性和可维护性,我建议以下内容:

    func (slc *mySlice) Remove1(item int) {
        s := *slc
        s = append(s[:item], s[item+1:]...)
        *slc = s
    }
    

    【讨论】:

    • 非常感谢斯蒂芬的快速回复!所以只是为了澄清一下,当将切片传递给函数/方法时,唯一被传递的是切片的 3 项结构定义(而不是底层数组)。当按值传递时,我传递了切片定义的副本,而当按首选项传递时,我传递了指向切片定义的指针?再次感谢!
    • 正确。当您传递一个值时,您将获得切片的 len、cap 和指向支持数组的指针的副本。当你传递一个指向 slice 的指针时,你可以修改原始的 len 和 cap。
    【解决方案2】:

    因为 append 不一定会返回相同的切片引用地址,正如 Stephen Weinberg 所指出的那样。 解决此限制的另一种方法是定义一个包装切片的结构。

    例如:

    package main
    
    import "fmt"
    
    type IntList struct {
        intlist []int
    }
    
    func (il *IntList) Pop() {
        if len(il.intlist) == 0 { return }
        il.intlist = il.intlist[:len(il.intlist)-1]
    }
    
    func (il *IntList) Add(i... int) {
        il.intlist = append(il.intlist, i...)
    }
    
    func (il *IntList) String() string {
        return fmt.Sprintf("%#v",il.intlist)
    }
    
    func main() {
        intlist := &IntList{[]int{1,2,3}} 
        fmt.Println(intlist)
        intlist.Pop()
        fmt.Println(intlist)
        intlist.Add([]int{4,5,6}...)
        fmt.Println(intlist)
    }
    

    输出:

    []int{1, 2, 3}
    []int{1, 2}
    []int{1, 2, 4, 5, 6}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2021-08-10
      • 2017-07-08
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多