gpt4 book ai didi

go - 在 Go for 循环的 post 部分中分配如何允许此循环退出?

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:33 25 4
gpt4 key购买 nike

我正在阅读“The Go Programming Language”一书,并在第 5 章中遇到了一个不寻常的 for 循环语法。我已经删减了下面的示例,但整个程序是 on the book's GitHub page .

type Node struct {
int NodeType
FirstChild, NextSibling *Node
}

func visit(n *Node) {
for c:= n.FirstChild; c != nil; c = c.NextSibling {
visit(c)
}
}

我脑海中的 C 解析器告诉我 c.NextSibling 将始终指向 Nodenil。在那种情况下,循环要么总是中断,要么永远继续。

c.NextSibling不是nil时,似乎循环退出了,因为循环值与上一次迭代相同,但我找不到Go Language Specification 中的任何内容来支持这一点。

我已经编译了那个程序并确认它按照书上的那样工作。

我是不是漏掉了一些基本的东西,还是这里发生了其他事情?


完整示例,带有检测代码(感谢 Sergio):

package main

import (
"fmt"
)

type Node struct {
NodeId int
FirstChild, NextSibling *Node
}

func visit(n *Node) {
fmt.Printf("Entering node %d\n", n.NodeId)
for c := n.FirstChild; c != nil; c = nextSib(c) {
fmt.Printf("Will now visit node %d\n", c.NodeId)
visit(c)
}
}

func nextSib(n *Node) *Node {
next := n.NextSibling
fmt.Printf("In nextSib for %d %t\n", n.NodeId, next != nil)
return next
}

func main() {
c4 := &Node{NodeId: 5}
c3 := &Node{NodeId: 4}
c2 := &Node{NodeId: 3, NextSibling: c3}
c1 := &Node{NodeId: 2, FirstChild: c4, NextSibling: c2}
root := &Node{NodeId: 1, FirstChild: c1}

visit(root)
}

输出:

Entering node 1
Will now visit node 2
Entering node 2
Will now visit node 5
Entering node 5
In nextSib for 5 false
In nextSib for 2 true
Will now visit node 3
Entering node 3
In nextSib for 3 true
Will now visit node 4
Entering node 4
In nextSib for 4 false

最佳答案

When c.NextSibling is not nil, it seems that the loop is exiting as the loop value is the same as the previous iteration

不确定您的意思,但是是的,您误解了某事。但是 for 循环不是罪魁祸首。肯定是does not exit而它的继续条件仍然为真。

type Node struct {
NodeId int
FirstChild, NextSibling *Node
}

func visit(n *Node) {
for c := n.FirstChild; c != nil; c = c.NextSibling {
fmt.Printf("seeing node %d\n", c.NodeId)
visit(c)
}
}

func main() {
c3 := &Node{NodeId: 4}
c2 := &Node{NodeId: 3, NextSibling: c3}
c1 := &Node{NodeId: 2, NextSibling: c2}
root := &Node{NodeId: 1, FirstChild: c1}

visit(root)
}

输出

seeing node 2
seeing node 3
seeing node 4

关于go - 在 Go for 循环的 post 部分中分配如何允许此循环退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54588706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com