在Golang中向切片追加指针

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

Appending a pointer to a Slice in Golang

问题

我想要将一个指针附加到一个切片中,这可能吗?在Parentnode.children中是一个切片,我想要用指针X将其附加上去。

func Tree(Parentnode *Node) {
    if IsvisitedNode(Parentnode.currentvalue - 1) {
        m := MovesArray[Parentnode.currentvalue-1]
        for j := 0; j < 8; j++ {
            if m[j] != 0 {
                var X *Node
                X.parentnode = Parentnode
                X.currentvalue = m[j]
                if IsvisitedNode(m[j]) {
                    Parentnode.children = append(Parentnode.children, *X)
                    Tree(X)
                }
            }
        }
    }
}

链接:https://play.golang.org/p/ghWtxWGOAU

英文:

I want to append a pointer to a slice.Is it possible..?In Partentnode.children is a slice I want to append it with X as pointer.

https://play.golang.org/p/ghWtxWGOAU

func Tree(Parentnode *Node) {
	if IsvisitedNode(Parentnode.currentvalue - 1) {
		m := MovesArray[Parentnode.currentvalue-1]
		for j := 0; j &lt; 8; j++ {
			if m[j] != 0 {
				var X *Node
				X.parentnode = Parentnode
				X.currentvalue = m[j]
				if IsvisitedNode(m[j]) {
					Parentnode.children = append(Parentnode.children, *X)
					Tree(X)
				}
			}
		}
	}
}

答案1

得分: 1

你有一个偏移错误。
在主函数中,你设置了 Y.currentvalue = 1
然后在 Tree 中,currentvalue 的值变成了 64

X.currentvalue = m[j]
fmt.Printf("cv: %v\n", X.currentvalue) // 变成了 64
if IsvisitedNode(m[j]) {

而在 IsvisitedNode 函数中,你将索引与 visithistory 进行比较,而 visithistory 具有 64 个索引,因此在索引 63 处停止,导致索引错误。

var visithistory [64]bool

func IsvisitedNode(position int) bool {
	if visithistory[position] == true {

如果你将 var visithistory [65]bool,那么问题就解决了,但我认为你需要重新思考一下这里的逻辑。

英文:

You have a off by one error.
In main you set Y.currentvalue = 1.
Then in Tree currentvalue walks to 64.

X.currentvalue = m[j]
fmt.Printf(&quot;cv: %v\n&quot;,X.currentvalue) //walks to 64
if IsvisitedNode(m[j]) {

An in IsvisitedNode you test that index against visithistory that has 64 indexes, thus stops at index 63. -> index error

var visithistory [64]bool

func IsvisitedNode(position int) bool {
	if visithistory[position] == true {

Things work if you set var visithistory [65]bool but I think you need to rethink you logic here somewhat.

huangapple
  • 本文由 发表于 2016年8月22日 15:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/39074031.html
匿名

发表评论

匿名网友

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

确定