Go语言中的引用类型容易混淆。

huangapple go评论76阅读模式
英文:

Reference type confusing in Go language

问题

我尝试使用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 following", 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"中出现了以下问题,即我在//Problem Point处:

我为搜索下一个链接的Trie创建了containsIndex方法,实际上它的搜索效果很好。但是,当我更新containsIndex返回的next属性时,它并没有影响到其母结构trie

我不明白的是,当返回containsIndex时,我给它的是引用类型,但它仍然像是“值复制”一样,为什么它不影响其母结构(trie)呢?

谢谢!

英文:

I tried to make Trie data structures by Go Language, but somehow it stuck with References problem,
Here it is. 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")
}

The following problems happen in second "Insert",
the where I put, //Problem Point

I made containsIndex method for searching next linked trie, and it searched well actually.
But when I updated next property which containsIndex given, its not affected its mother struct trie though.

What I don't understand is I gave it reference type when returning containsIndex, but its still
act liked 'value copied', Why does it not affected its mother structure(trie)?

Thanks!

答案1

得分: 3

问题出在containsIndex方法中。Golang的range默认会为切片中的每个元素创建一个副本,并将该值的副本赋给st(在你的示例中)。通常,为了保留对切片中元素的引用,你应该使用原始切片及其索引。在你的情况下,containsIndex方法应该像这样:

func (trie *Trie) containsIndex(next string) *Trie {
    if next != "" {
        for i := range trie.subtrie {
            if trie.subtrie[i].index == next[0] {
                return &trie.subtrie[i]
            }
        }
    }
    return nil
}
英文:

The problem is in method containsIndex. Golang range by default creates copy each element in slice and assigns copy of this value to st (in your example). Usually to preserve reference to element in slice you should use original slice and its index. In you case method containsIndex should look something like this:

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
}

huangapple
  • 本文由 发表于 2014年12月30日 14:13:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/27700487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定