벡터 할당은 값 또는 Google의 Go Language에서 참조로 복사됩니까?

StackOverflow https://stackoverflow.com/questions/1806673

  •  05-07-2019
  •  | 
  •  

문제

다음 코드에서, 나는 하나의 페그 퍼즐을 만들고, 움직임을 수행하여 MovesAlreadyDone 벡터에 이동을 추가합니다. 그런 다음 다른 페그 퍼즐을 만들고 움직임을 수행하여 MovesAlreadyDone 벡터에 이동을 추가합니다. 두 번째 벡터의 값에 값을 인쇄하면 두 번째 값과 함께 첫 번째 값에서 이동할 수 있습니다. 누구든지 왜 그것이 가치가 아닌 참조로 할당되는 것처럼 보이는지 말해 줄 수 있습니까? 벡터 할당은 값 또는 Google의 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----------------------\n");
    fmt.Printf("moves already done: %v\n", p.movesAlreadyDone);
    fmt.Printf("------------END-----------------------\n");
}

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();
}

모든 도움은 대단히 감사하겠습니다. 감사!

도움이 되었습니까?

해결책

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.

다른 팁

In your code, movesAlreadyDone is a *vector.Vector; when you assign retVal.movesAlreadyDone = parent.movesAlreadyDone;, you are copying a reference. Anytime a vector modification is done on either retVal.movesAlreadyDone or parent.movesAlreadyDone you'll be modifying the same underlying vector.

If you want to copy the contents of one vector to another you will need to iterate through the source vector and push its elements to the destination vector. Like so:

for n := range srcVect.Iter() {
    dstVect.Push(n);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top