Go指针类型的参数传递机制

go 指针类型参数传递有两种方式:值传递:函数获得指针副本,对副本的更改不影响原始指针。引用传递:函数获得对原始指针的引用,对引用的更改影响原始指针。

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
}
登录后复制

在第一个示例中,我们使用值传递创建链表。在第二个示例中,我们使用引用传递创建链表。执行结果都是相同的,但使用引用传递时,我们可以在函数中修改链表的顺序。

以上就是Go指针类型的参数传递机制的详细内容,更多请关注小编网其它相关文章!

转载请说明出处 内容投诉内容投诉
南趣百科 » Go指针类型的参数传递机制

南趣百科分享生活经验知识,是您实用的生活科普指南。

查看演示 官网购买