我尝试用 Go 语言制作 Trie 数据结构,但不知何故它遇到了引用问题, 这里是。 http://play.golang.org/p/ASSGF5Oe9R
// Package main provides ...
package main
import "fmt"
type RootTrie []Trie
type Trie struct {
subtrie []Trie
index byte
}
func (trie *Trie) Insert(data string) *Trie {
if data != "" {
if trie.index == 0 {
trie.index = data[0]
}
if next := trie.containsIndex(data[1:]); next != nil {
//Problem Point
fmt.Println(string(data[1]), "found follwing", string(data[0]))
next.Insert(data[1:])
} else {
nt := &Trie{}
trie.subtrie = append(trie.subtrie, *nt.Insert(data[1:]))
}
}
return trie
}
func (trie *Trie) containsIndex(next string) *Trie {
if next != "" {
for _, st := range trie.subtrie {
if st.index == next[0] {
return &st
}
}
}
return nil
}
func main() {
t := &Trie{}
t = t.Insert("hanyang")
fmt.Println("result:", t)
t = t.Insert("hanyKk")
fmt.Println("result:", t)
t.Insert("hanyK")
}
第二次“Insert”出现如下问题,
我放的地方,//问题点
我制作了 containsIndex
方法来搜索下一个链接的 trie,实际上它搜索得很好。
但是,当我更新 containsIndex
给出的 next
属性时,它并没有影响它的母结构 trie
。
我不明白的是我在返回containsIndex
时给了它引用类型,但它仍然
act like 'value copyed',为什么它不影响它的母结构(trie
)?
谢谢!
最佳答案
问题出在方法 containsIndex 中。 Golang range
默认情况下创建复制 slice 中的每个元素并将该值的副本分配给 st
(在您的示例中)。通常要保留对 slice 中元素的引用,您应该使用原始 slice 及其索引。在你的情况下,方法 containsIndex 应该看起来像这样:
func (trie *Trie) containsIndex(next string) *Trie {
if next != "" {
for i, st := range trie.subtrie {
if st.index == next[0] {
return &trie.subtrie[i]
}
}
}
return nil
}
关于go - Go 语言中的引用类型令人困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27700487/