Home > Article > Backend Development > Go pointer type parameter passing mechanism
There are two ways to pass pointer type parameters in Go: value passing: the function obtains a copy of the pointer, and changes to the copy do not affect the original pointer. Pass by reference: The function obtains a reference to the original pointer, and changes to the reference affect the original pointer.
Go pointer type parameter passing mechanism
In Go, pointer type parameters are passed to functions in two different ways: Passing by value and passing by reference.
Value passing
If you pass a pointer value to a function as a value, the function will get a copy of the pointer. Any changes made to this copy will not affect the original pointer.
Code example:
package main import "fmt" func changeValue(ptr *int) { *ptr = 10 } func main() { ptr := new(int) *ptr = 5 fmt.Println(*ptr) // 输出: 5 changeValue(ptr) fmt.Println(*ptr) // 输出: 5 }
Pass by reference
If you pass a pointer address to a function as a value, the function will get A reference to a raw pointer. Any changes made to this reference will affect the original pointer.
Code example:
package main import "fmt" func changePointer(ptr **int) { *ptr = new(int) **ptr = 10 } func main() { ptr := new(int) *ptr = 5 fmt.Println(*ptr) // 输出: 5 changePointer(&ptr) fmt.Println(*ptr) // 输出: 10 }
Practical case
In the following practical case, we use value passing and reference passing to Implement a simple linked list.
Implementing a linked list using passing by value:
type Node struct { value int next *Node } func createList(values []int) *Node { head := &Node{value: values[0]} current := head for _, v := range values[1:] { next := &Node{value: v} current.next = next current = next } return head } func printList(head *Node) { for current := head; current != nil; current = current.next { fmt.Printf("%d ", current.value) } fmt.Println() } func main() { values := []int{1, 2, 3, 4, 5} head := createList(values) printList(head) // 输出: 1 2 3 4 5 }
Implementing a linked list using passing by reference:
type Node struct { value int next **Node } func createList(values []int) *Node { head := &Node{value: values[0]} current := head for _, v := range values[1:] { next := &Node{value: v} *current.next = next current = next } return head } func printList(head *Node) { for current := head; current != nil; current = *current.next { fmt.Printf("%d ", current.value) } fmt.Println() } func main() { values := []int{1, 2, 3, 4, 5} head := createList(values) printList(head) // 输出: 1 2 3 4 5 }
In the first example , we create a linked list using value passing. In the second example, we create a linked list using pass-by-reference. The execution results are the same, but when passing by reference, we can modify the order of the linked list in the function.
The above is the detailed content of Go pointer type parameter passing mechanism. For more information, please follow other related articles on the PHP Chinese website!