dqxm14187 2018-02-26 13:29
浏览 66
已采纳

在变量期间转到切片指针更改附加行为

I'm a bit confused as to why this happens when attempting to remove an element from a slice in Go.

As a simplified example, I have the following data structures:

type Person struct {
    Name string
}

type People []Person

I want to add a method to remove a person with a certain name from the list of people with people.Remove("Sam"):

func (p *People) Remove(name string) {
    for i, person := range *p {
        if person.Name == name {
            // Doesn't work
            *p = append(*p[:i], *p[i+1:]...)
        }
    }
}

I thought this would work, but referencing the slice elements in this manner returns a compile error: cannot slice p (type *People).

So, fair enough. But when I set *p to another variable (a), it works exactly as expected:

func (p *People) Remove(name string) {
    for i, person := range *p {
        if person.Name == name {
            // Does work
            a := *p
            *p = append(a[:i], a[i+1:]...)
        }
    }
}

Why do I need to set the slice to a difference variable before this method works? Shouldn't the behaviour be exactly the same?

I'm probably misunderstanding something fundamental here so if anyone can explain why this is required I'd love to know. Thank you!

  • 写回答

1条回答 默认 最新

  • doucaigai7176 2018-02-26 13:39
    关注

    The slice expressions in *p = append(*p[:i], *p[i+1:]...) take precedence over the * operator. You need to enclose those in parentheses.

    func (p *People) Remove(name string) {
        for i, person := range *p {
            if person.Name == name {
                // Doesn't work
                *p = append((*p)[:i], (*p)[i+1:]...)
            }
        }
    }
    

    https://play.golang.org/p/cbT65mCzA4h

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan