Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试在Go中测试空的自引用结构值_Go_Struct - Fatal编程技术网

尝试在Go中测试空的自引用结构值

尝试在Go中测试空的自引用结构值,go,struct,Go,Struct,我是新手,正在尝试实现一个非常简单的链表。当前,在递归遍历列表时,我试图在node.next为nil/unset时中断for循环,但if条件从未满足。我只能假设该值不是nil,而是指向空节点结构类型的某种指针,但我不知道如何计算它。这是我的代码,任何帮助都将不胜感激: package main import "fmt" type Node struct { data string next *Node } func PrintList(node *Node) { for

我是新手,正在尝试实现一个非常简单的链表。当前,在递归遍历列表时,我试图在node.next为nil/unset时中断for循环,但if条件从未满足。我只能假设该值不是nil,而是指向空节点结构类型的某种指针,但我不知道如何计算它。这是我的代码,任何帮助都将不胜感激:

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)
}

修正您的输入错误:
node.next==nil
not
node.data==nil
。并修复递归错误:删除
for
循环。更好的是,为了安全起见,检查节点==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