doujiku1028 2014-05-02 05:12
浏览 23
已采纳

Golang指针作为方法参数

I am working with golang's pointers the way I did with c++, but it seems not to work, which would be the right way to do it? or what am I doing wrong?, Thanks.

ftw I'm doing 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
}

nil

nil

nil

TEST PASS

  • 写回答

1条回答 默认 最新

  • dongwu5801 2014-05-02 10:19
    关注

    In your insert function you have:

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

    This updates the local variable t, but will not change the variable passed in the calling scope since Go passes function parameters by value. So when you make the following call:

    insert(t.Left, item, done)
    

    if t.Left is nil, its value will not be changed by the function call. If you do want it to update the variable, you'll need to define the function argument as t **Tree, change references to set *t instead, and change the call to:

    insert(&t.Left, item, done)
    

    There is no equivalent to C++'s syntax for passing function arguments by reference: instead you need to be explicit when passing pointers.

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀