Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a void* in golang? [duplicate]

Tags:

go

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

like image 459
Charles Shiller Avatar asked Feb 07 '23 12:02

Charles Shiller


1 Answers

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>}
like image 165
Plato Avatar answered Feb 19 '23 18:02

Plato