2016-05-21 17:44

# Golang：递归数据结构

• IT行业问题
• 计算机技术
• it技术
• 编程语言问答
• 互联网问答

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?

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

#### 2条回答

• doupi3874 5年前

Is this what you're looking for?

点赞 评论 复制链接分享
• doujiang2643 5年前

TLDR: I think it is possible

``````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 `Trie`s 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

点赞 评论 复制链接分享