尝试在Go中测试一个空的自引用结构体值。

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

Trying to test for an empty self referential struct value in Go

问题

我是你的中文翻译助手,以下是翻译好的内容:

我刚开始学习Go语言,尝试实现一个非常简单的链表。目前,在递归遍历链表时,我试图在node.next为nil/未设置时跳出for循环,但是if条件从未满足。我只能假设该值不是nil,而是指向一个空的Node结构体类型的指针,但我无法确定如何评估它。这是我的代码,非常感谢任何帮助:

package main

import "fmt"

type Node struct {
    data string
    next *Node
}

func PrintList(node *Node) {
  for {
    fmt.Println(node.data)

    if node.next == nil {
      break
    } else {
      PrintList(node.next)
    }
  }
}

func main() {
  node3 := &Node{data: "three"}
  node2 := &Node{data: "two", next: node3}
  node1 := &Node{data: "one", next: node2}

  PrintList(node1)
}

请注意,我已经更正了代码中的一个错误。在条件判断中,应该使用node.next == nil而不是node.data == nil来检查下一个节点是否为空。

英文:

I am new to Go and am trying to implement a very simple linked list. Currently while recursively traversing the list I am attempting to break out of the for loop if node.next is nil/unset, but the if conditional is never satisfied. I can only assume that the value is not nil, but some sort of pointer to an empty Node struct type, but I can't figure out how to evaluate this. Here is my code, any help would be much appreciated:

package main

import "fmt"

type Node struct {
    data string
    next *Node
}

func PrintList(node *Node) {
  for {
    fmt.Println(node.data)

    if node.data == nil {
      break
    } else {
      PrintList(node.next)
    }
  }
}

func main() {
  node3 := &Node{data: "three"}
  node2 := &Node{data: "two", next: node3}
  node1 := &Node{data: "one", next: node2}

  PrintList(node1)
}

答案1

得分: 3

修正你的拼写错误:node.next == nil 而不是 node.data == nil。并修复你的递归错误:删除 for 循环。更好的做法是,为了安全起见,检查 node == nil。例如,

package main

import "fmt"

type Node struct {
    data string
    next *Node
}

func PrintList(node *Node) {
    if node == nil {
        return
    }
    fmt.Println(node.data)
    PrintList(node.next)
}

func main() {
    node3 := &Node{data: "three"}
    node2 := &Node{data: "two", next: node3}
    node1 := &Node{data: "one", next: node2}
    PrintList(node1)
}

输出:

one
two
three
英文:

Fix your typo: node.next == nil not node.data == nil. And fix your recursion error: delete the for loop. Even better, for safety, check for node == nil. For example,

package main

import "fmt"

type Node struct {
	data string
	next *Node
}

func PrintList(node *Node) {
	if node == nil {
		return
	}
	fmt.Println(node.data)
	PrintList(node.next)
}

func main() {
	node3 := &Node{data: "three"}
	node2 := &Node{data: "two", next: node3}
	node1 := &Node{data: "one", next: node2}
	PrintList(node1)
}

Output:

one
two
three

huangapple
  • 本文由 发表于 2016年3月5日 22:23:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/35815248.html
匿名

发表评论

匿名网友

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

确定