douyou7797 2015-01-25 04:38
浏览 272
已采纳

Golang中的数组子集

I am trying to write the equivalent of the following line in python

H = [e for e in G if condition(e)]

Here is my example code. Basically I am just trying to use a getter function (G.get) to get a subset of G. So I think I want arr2 to be a new array but containing the same object.

package main

import "fmt"

type Object struct {
    x int
}

type Group []Object

func (G *Group) get() (H []Object) {
    for _,v := range *G {
        H = append(H,v)
    }
    return
}

func main() {
    arr := make(Group,1)
    arr[0].x = 1
    fmt.Println(arr)
    arr2 := arr.get()
    arr[0].x = 3
    fmt.Println(arr)
    fmt.Println(arr2)
}

Which compiles and runs and gives me

[{1}]
[{3}]
[{1}]

My question is "Why does arr2 not contain the same instance of an Object as arr?" I believe I understand make only instantiates a Group thing which means it includes one Object in it. But then the for loop shouldn't create a new Object should it?

Thanks for the help!

  • 写回答

1条回答 默认 最新

  • donglengyuan6826 2015-01-25 04:50
    关注

    This simpler snippet of code shows what's going on:

    var a Object
    a.x = 1
    b := a
    fmt.Println(a, b) // prints {1} {1}
    b.x = 2
    fmt.Println(a, b) // prints {1} {2}
    

    playground example

    The statement b := a copies the Object value in variable a to the variable b. There are now two copies of the value. Changing one does not change the other.

    This is different from Python where assignment copies a reference to a value.

    The loop in the question also copies the values:

    for _,v := range *G {
        H = append(H,v)
    }
    

    The variable v is a copy the slice element from *G. A copy of v is appended to slice H. There are three independent Object values: the value in slice *G, the value in v and the value in slice H.

    If you want the slices to all refer to the same Object value, then store pointers to Object values in the slice:

    type Group []*Object
    
    arr := make(Group, 1)
    arr[0] = &Object{x: 1}
    fmt.Println(arr[0].x)  // prints 1
    arr2 := arr.get()
    arr[0].x = 3
    fmt.Println(arr[0].x)  // prints 3
    fmt.Println(arr2[0].x) // prints 3
    

    playground example

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

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题