doudizhi947129 2016-04-29 01:58
浏览 31

附加到切片的多个实例

If I have two pointers to slices s1, s2, which initially point to the same slice, is it possible to append to one of the slices and have the other slice also point to the updated slice? This seems to be a problem because, appending to slices might make a new slice with the entries copied over if the capacity is insufficient.

The following is a slightly complicated version on the Go Playground that is closer to my use case. Namely, I have nodes that have a pointer to a (global) queue which is implemented by a slice. When one node updates the global queue, I want that to be reflected in the slice that the other node points to.

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

  • 写回答

1条回答 默认 最新

  • douzhicai7148 2016-04-29 02:56
    关注

    Add a indirect layer, i.e. a pointer, can help you work this out https://play.golang.org/p/R7JILCbYTF

    package main
    
    import (
        "fmt"
    )
    
    type queue *[]int
    
    type node struct {
        id int
        list *queue
    }
    
    func (n *node) mutate(){
        newSlice := append(**n.list, 1)
        *n.list = &newSlice
    }
    func (n *node) get(idx int) int{
        return (*(*[]int)(*n.list))[idx]
    }
    
    func main() {
        /* Make empty queue */
        s:=make([]int, 0)
        q1:=queue(&s)
        fmt.Println(q1)
    
        /* Make new nodes */
        n1 := new(node)
        n1.id = 0
        n1.list = &q1
        fmt.Println(n1)
    
        n2 := new(node)
        n2.id = 1
        n2.list = n1.list
        fmt.Println(n2)
    
        /* Mutate node in n1 */
        n1.mutate()
        fmt.Println(n1, n2) // n1.list != n2.list
        fmt.Println(n1.list, n2.list)
        fmt.Println(n1.get(0))
        n2.mutate()
        fmt.Println(n2.get(0))
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题