在链接列表的末尾插入项目

I am very new to go and deicide to implement a linked list. Here is my source code

package main

import "fmt"

type Node struct {
  value int
  next *Node
}

func main() {

  var head *Node
  for i := 1; i <= 10; i++ {
    insert(&head, i)
  }

  print_list(head)
}

func print_list(node_pointer *Node) {
  if (node_pointer == nil) {
    return
  } else {
    node := *node_pointer
    fmt.Printf("%d
", node.value)
    print_list(node.next)
  }
}

func insert(node_pointer **Node, // pointer to a pointer to a Node
    value int) {
  var new_node Node
  new_node.value = value

  if (*node_pointer == nil) {
    fmt.Printf("Empty list
")
    *node_pointer = &new_node
  } else {
    var cur_node Node = **node_pointer
    for cur_node.next != nil {
      cur_node = *cur_node.next
    }
    cur_node.next = &new_node
    fmt.Printf("Add %d
", (*cur_node.next).value)      }
}

The output is:

Empty list
Add 2
Add 3
Add 4
Add 5
Add 6
Add 7
Add 8
Add 9
Add 10
1

In other words, I cannot insert a new Node at the end of the linked list. I believe that it is caused by cur_node.next = &new_node which only makes the update locally, but don't know how to fix this.

The problem is in your insert function - here is a corrected version

func insert(node_pointer **Node, // pointer to a pointer to a Node
    value int) {
    var new_node Node
    new_node.value = value

    if *node_pointer == nil {
        fmt.Printf("Empty list
")
        *node_pointer = &new_node
    } else {
        var cur_node *Node = *node_pointer
        for cur_node.next != nil {
            cur_node = cur_node.next
        }
        cur_node.next = &new_node
        fmt.Printf("Add %d
", (*cur_node.next).value)
    }
}

Playground

Your error is because you get the node value,not the pointer here:

    var cur_node Node = **node_pointer

*note_pointer is a pointer pointed to head of list,but you are using **node_pointer,then you get the value,then copy this value to cur_node, afterwards new node will be append to cur_node,no relevant to head node.So when your print form head node,you can only get the value of the head node.

The fixed solution is like @Nick Craig-Wood said.