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

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?