go - Go 语言中的引用类型令人困惑

标签 go pass-by-reference pass-by-value trie pass-by-name

我尝试用 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/

相关文章:

go - 如何使用 Go Templates (Helm) 应用递归格式?

google-app-engine - Golang CSV error bare "in non-quoted-field

C++ 指针传递和值修改

c++ - 如何将 vector 从成员函数传递给同一类中的另一个成员函数?

c++ - 当我在C++中存储指向按值传递参数的指针时会发生什么?

java - Java 中的基元与对象

networking - 如何获取 (IPv4) net.IPNet 的广播地址?

linux - 如何从 CentOS 中删除 golang 包

c++ - sf::Sprite 是白色矩形(纹理试图通过引用传递)

java - Java 是 "pass-by-reference"还是 "pass-by-value"?