dousui6488 2017-11-16 23:00 采纳率: 100%
浏览 10

如何在go中表达C ++逻辑的“新”运算符?

I have a structure like this

type Node struct {
    data int
    next *Node
}

var root Node;

I would like to create a tmp Node and pass the address to root.next, how to write this kind of logic in go?

root.next = Node
  • 写回答

1条回答 默认 最新

  • doujiang3997 2017-11-16 23:03
    关注

    There are no constructors in Go. You just create an object by using the type name and you can set the fields at the same time.

    tmp := Node {
        data: 1
    }
    root.next = &tmp
    

    You can also take a pointer to a new object.

    tmp := &Node {
        data: 1
    }
    root.next = tmp
    

    And then put it all together.

    root.next = &Node {
        data: 1
    }
    

    There is also a new operator which is equivalent to &Node{} and therefore it is not very convienent as you need to assign field values later.

    评论

报告相同问题?