go 指針類型參數傳遞有兩種方式:值傳遞:函數獲得指針副本,對副本的更改不影響原始指針。引用傳遞:函數獲得對原始指針的引用,對引用的更改影響原始指針。
Go 指針類型參數傳遞機制
在 Go 中,指針類型參數以兩種不同的方式傳遞給函數:值傳遞和引用傳遞。
值傳遞
如果將指針值作為值傳遞給函數,則函數將獲得該指針的副本。對該副本所做的任何更改都不會影響原始指針。
代碼示例:
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
}
登錄后復制
引用傳遞
如果將指針地址作為值傳遞給函數,則函數將獲得對原始指針的引用。對該引用所做的任何更改都會影響原始指針。
代碼示例:
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
}
登錄后復制
實戰案例
在以下實戰案例中,我們使用值傳遞和引用傳遞來實現一個簡單的鏈表。
使用值傳遞實現鏈表:
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
}
登錄后復制
使用引用傳遞實現鏈表:
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
}
登錄后復制
在第一個示例中,我們使用值傳遞創建鏈表。在第二個示例中,我們使用引用傳遞創建鏈表。執行結果都是相同的,但使用引用傳遞時,我們可以在函數中修改鏈表的順序。






