2016-07-20 23:04 阅读 279

如何在golang中实现void *? [重复]

This question already has an answer here:

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dtv995719 dtv995719 2016-07-21 00:17

    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 (
    type Node struct {
        List []*Node
        Data interface{}
    func main() {
        trivial := Node{}
        leaf := Node{Data: 1}
        tree := Node{
            List: []*Node{
    func out(x interface{}) {
    ", x, x)
    // main.Node:{List:[] Data:<nil>}
    // main.Node:{List:[] Data:1}
    // main.Node:{List:[0xc82000e180 0xc82000e180] Data:<nil>}
    点赞 评论 复制链接分享
  • doujiang1993 doujiang1993 2016-07-20 23:12

    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

    点赞 评论 复制链接分享