douyue3800 2009-11-27 04:07
浏览 19
已采纳

向量分配是通过值还是通过引用以Google的Go语言复制的?

In the following code, I create one peg puzzle then do a move on it which adds a move to its movesAlreadyDone vector. Then I create another peg puzzle then do a move on it which adds a move to its movesAlreadyDone vector. When I print out the values in that vector for the second one, it has the move in it from the first one along with the move from the second one. Can anyone tell me why it seems to be assigning by reference and not value? Are vector assignments copied by value or by reference in Google's Go language?

package main

import "fmt"
import "container/vector"

type Move struct { x0, y0, x1, y1 int }

type PegPuzzle struct {
    movesAlreadyDone * vector.Vector;
}

func (p *PegPuzzle) InitPegPuzzle(){
    p.movesAlreadyDone = vector.New(0);
}

func NewChildPegPuzzle(parent *PegPuzzle) *PegPuzzle{
    retVal := new(PegPuzzle);
    retVal.movesAlreadyDone = parent.movesAlreadyDone;
    return retVal
}

func (p *PegPuzzle) doMove(move Move){
    p.movesAlreadyDone.Push(move);
}

func (p *PegPuzzle) printPuzzleInfo(){
    fmt.Printf("-----------START----------------------
");
    fmt.Printf("moves already done: %v
", p.movesAlreadyDone);
    fmt.Printf("------------END-----------------------
");
}

func main() {
    p := new(PegPuzzle);
    cp1 := new(PegPuzzle);
    cp2 := new(PegPuzzle);

    p.InitPegPuzzle();

    cp1 = NewChildPegPuzzle(p);
    cp1.doMove(Move{1,1,2,3});
    cp1.printPuzzleInfo();

    cp2 = NewChildPegPuzzle(p);
    cp2.doMove(Move{3,2,5,1});
    cp2.printPuzzleInfo();
}

Any help will be greatly appreciated. Thanks!

  • 写回答

2条回答 默认 最新

  • douwei7471 2009-11-27 05:28
    关注

    Incidental to the answer, but vector.New has been deleted from recent versions of Go. You need to write

    func (p *PegPuzzle) InitPegPuzzle(){
        p.movesAlreadyDone = new (vector.Vector);
    }
    

    In your original code, the things you are copying are pointers to vectors. This is just the same as pointers in C. You can call it "by reference" if you like, but they're pointers.

    To copy an entire vector, use InsertVector:

    func (p *PegPuzzle) InitPegPuzzle(){
        p.movesAlreadyDone = new (vector.Vector);
    }
    
    func NewChildPegPuzzle(parent *PegPuzzle) *PegPuzzle{
        retVal := new (PegPuzzle);
        retVal.InitPegPuzzle ();
        retVal.movesAlreadyDone.InsertVector (0, parent.movesAlreadyDone);
        return retVal
    }
    

    This gives a complete unique copy.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。