2014-05-02 63 views
0

我正在与golang的指针一起使用C++的方式,但它似乎不工作,这将是正确的方法吗?或者我做错了什么?谢谢。Golang指针作为方法参数

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 
} 

检验合格

+1

什么不工作?那么,除了明显的事情,例如调用'insert(t.Left,done)'到一个带有三个参数的函数。 – ANisus

+0

关闭完成而不发送任何信号。 –

+0

排字错误我做了一个结帐,所以我复制错误在这里,我关闭通道,因为该项目已经存在,所以没有完成信号 – sescob27

回答

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++的语法通过引用传递函数参数:相反,您需要在传递指针时进行显式指定。