G4143
G4143

Reputation: 2829

Golang: Recursive data structures

I have a simple question... I'm trying to reproduce this recursive data structure in Golang with slices.

type Trie map[byte]Trie

Right now I have some 'rough' source code using the recursive data structure below with slices and everything works fine except my typed structure is a structure and not a slice of structures. Ideally I would like my typed recursive data structure to be a slice of Trie's which has elements Trie{byte, []Trie}. Hope that makes sense? Right now I have a type which is a Trie struct{byte, []Trie}.

type Trie struct {
elem byte
others []Trie
} 

Maybe this will help. When I create my Trie of slices right now I use this function.

func CreateTrie() []Trie {
    return make([]Trie, 0, 13)
}

I would like to have the Trie of slices defined in such a way that I could create the slices like this.

func CreateTrie() Trie {
    return make(Trie, 0, 13)
}

Is this possible with slices or do I have use my first(only) solution for slices?

Upvotes: 5

Views: 3772

Answers (2)

poopoothegorilla
poopoothegorilla

Reputation: 784

TLDR: I think it is possible

Using your Trie struct

type Trie struct {
    elem byte
    others []*Trie
}

Here is a modified createTrie constructor. I wasn't sure if you wanted to show a chain of Tries so I figured to pass level just as an example.

func createTrie(levels int) *Trie {
    result := &Trie{
        others: make([]*Trie, 0, 13),
    }
    for level := 0 ;level < levels; level++ {
        result.others = append(result.others, createTrie(levels - 1))
    }

    return result
}

https://play.golang.org/p/-GRm0tV-B1

Upvotes: 1

jnmoal
jnmoal

Reputation: 1015

Is this what you're looking for?

Upvotes: 2

Related Questions