我試圖用 Go 語言制作 Trie 數(shù)據(jù)結(jié)構(gòu),但不知何故它遇到了引用問題,就是這樣。http://play.golang.org/p/ASSGF5Oe9R// Package main provides ...package mainimport "fmt"type RootTrie []Trietype 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")}以下問題發(fā)生在我放置的第二個“插入”中, //Problem Point我制定containsIndex了搜索下一個鏈接trie的方法,實際上搜索得很好。但是當我更新給定的next屬性時containsIndex,它并沒有影響它的母結(jié)構(gòu)trie。我不明白的是我在返回時給了它引用類型containsIndex,但它仍然表現(xiàn)得像“復制值”,為什么它不影響它的母結(jié)構(gòu)(trie)?
1 回答

守候你守候我
TA貢獻1802條經(jīng)驗 獲得超10個贊
問題出在方法 containsIndex 中。range默認情況下,Golang創(chuàng)建切片中的每個元素的副本,并將此值的副本分配給st(在您的示例中)。通常要保留對切片中元素的引用,您應該使用原始切片及其索引。在你的情況下,方法 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
}
- 1 回答
- 0 關(guān)注
- 225 瀏覽
添加回答
舉報
0/150
提交
取消