5

I'm making a (non-binary) tree in Golang.

In Java, I'd use something like

 class Node{
   List <Object> data;
 }

Where data can be either a pointer to data or to a child node

In C or C++, I'd use a void*.

What type should I use in golang

Charles Shiller
  • 1,013
  • 4
  • 13
  • 32

2 Answers2

4

There are no void pointers in Go. The way to handle this is by using the empty interface interface{} which is inherently implemented by all types. I asked a question about this awhile back which you can find here; Go equivalent of a void pointer in C

Community
  • 1
  • 1
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • 3
    There's also unsafe.Pointer which is, well, less safe because it can be coerced into an arbitrary type. You're right that `interface{}` is more akin to `Object` though as it's simply a type that every other type "is". – Linear Jul 20 '16 at 23:15
  • Late to the party, but for the convenience of anyone else reading this, @LinearZoetrope sure, but you can make them safe with a [Type Assertion](https://stackoverflow.com/questions/14289256/cannot-convert-data-type-interface-to-type-string-need-type-assertion). – glowkeeper Apr 28 '20 at 18:57
4

I've never tried to solve this problem in any language, would this work in Go?

go play link edit after reading the duplicate question i see you're not asking about the implementation, enjoy anyway ♥︎

package main

import (
    "fmt"
)

type Node struct {
    List []*Node
    Data interface{}
}

func main() {
    trivial := Node{}

    leaf := Node{Data: 1}

    tree := Node{
        List: []*Node{
            &leaf,
            &leaf,
        },
    }
    out(trivial)
    out(leaf)
    out(tree)
}

func out(x interface{}) {
    fmt.Printf("%T:%+v\n", x, x)
}

// main.Node:{List:[] Data:<nil>}
// main.Node:{List:[] Data:1}
// main.Node:{List:[0xc82000e180 0xc82000e180] Data:<nil>}
Plato
  • 10,812
  • 2
  • 41
  • 61