Golang Pointers作为方法参数

时间:2014-05-02 05:12:34

标签: pointers go

我正在使用golang的指针,就像我使用c ++一样,但它似乎不起作用,这是正确的方法吗?或者我做错了什么?,谢谢。

ftw我正在做AsyncBinaryTrees。

type Obj interface {
    Compare(node Obj) int
}

type Tree struct {
    Item        Obj
    Rigth, Left *Tree
    height      int16
}

func Insert(t *Tree, item Obj) chan struct{} {
    done := make(chan struct{}, 1)
    go insert(t, item, done)
    return done
}

func insert(t *Tree, item Obj, done chan struct{}) {
    if t == nil {
        t = &Tree{Item: nil, Rigth: nil, Left: nil, height: 0}
        var signal struct{}
        done <- signal
        close(done)
    } else {
        if t.Item.Compare(item) == 1 { //Left
            insert(t.Left, item, done)
        } else if t.Item.Compare(item) == -1 { //Rigth
            insert(t.Right, item, done)
        } else {
            close(done)
            panic
        }
    }
}

//=== testing

func assertSignal(ch_signal chan struct{}, t *testing.T) {
    _, done := <-ch_signal
    if !done {
        t.Error("Error: it should send a signal of empty struct")
    }
}

func TestInsertion(t *testing.T) {
    var tree *Tree
    ch_signal := Insert(tree, newObjInt())
    fmt.PrintLn(t)             //=> <nil>
    assertSignal(ch_signal, t) //=>PASS
    ch_signal = Insert(tree, newObjInt())
    fmt.PrintLn(t)             //=> <nil>
    assertSignal(ch_signal, t) //=>PASS
    ch_signal = Insert(tree, newObjInt())
    fmt.PrintLn(t)             //=> <nil>
    assertSignal(ch_signal, t) //=>PASS
    ch_signal = Insert(tree, newObjInt())
    assertSignal(ch_signal, t) //=>PASS
}

TEST PASS

1 个答案:

答案 0 :(得分:3)

在您的insert功能中:

func insert(t *Tree, item Obj, done chan struct{}) {
    if t == nil {
        t = &Tree{Item: nil, Rigth: nil, Left: nil, height: 0}
    ...
}

这会更新局部变量t,但不会更改调用范围中传递的变量,因为Go会按值传递函数参数。所以当你拨打以下电话时:

insert(t.Left, item, done)

如果t.Leftnil,则函数调用不会更改其值。如果您确实希望它更新变量,您需要将函数参数定义为t **Tree,更改引用以设置*t,并将调用更改为:

insert(&t.Left, item, done)

通过引用传递函数参数没有等效于C ++的语法:相反,在传递指针时需要显式。