go - golang中指针内容的差异

标签 go

考虑以下结构和指针引用示例的代码。

package main

import (
    "fmt"
    "sync"
)

type myStruct struct {
    mut *sync.RWMutex
}

type arrayOfMyStruct struct {
   structList []myStruct
}


func main() {
    k := &sync.RWMutex{}    
    myStructInstance := myStruct{k}
    fmt.Printf("%p", &k) // address 1 -> address of k
    fmt.Println("")
    fmt.Printf("%p", &*k) // address 2 -> address of what k points to
    fmt.Println("")

    var listStruct []myStruct

    listStruct = append(listStruct, myStructInstance)

    test := &arrayOfMyStruct{listStruct}

    test.access()
}

func (elem *arrayOfMyStruct) access() {
    mystructinstance := &elem.structList[0]
    mystructinstance2 := elem.structList[0]
    fmt.Println(&mystructinstance.mut) // address 3
    fmt.Println(&mystructinstance2.mut) // address 4
}

为什么地址 2 3 和 4 不同?它们不应该相同吗?

最佳答案

因为myStruct中的mut已经是一个指针*sync.RWMutex,所以当你这样做的时候:

&mystructinstance2.mut

您实际上得到了一个指向 mut 的新指针,它是一个指向类似于 **sync.RWMutex 的互斥锁的指针。只需删除打印语句中的 & 即可。当您使用 k := &sync.RWMutex{} 创建互斥量时,它已经是一个指针,因此您不应在该变量之后的任何地方使用 & ,否则它将创建一个指向该指针的新指针。您还可以使用 k := new(sync.RWMutex) 创建指向新互斥锁的指针。

您可以在 Printf 上使用 %p 来打印指针地址:

fmt.Printf("%p\n", mystructinstance2.mut)

关于go - golang中指针内容的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45787405/

相关文章:

go - Paho MQTT Golang 协议(protocol)

Go: 将 var 传递给匿名函数

go - 将 append() 附加到另一个线程正在读取的 slice 是否安全?

go - 实现 Less() 时处理错误的正确方法

go - 您应该使用 protobuf 作为用于处理还是仅用于传输的数据类型?

go - Google Cloud Storage go客户端中的重试逻辑在哪里?

去1.17 : How to log error with the stack trace

json - 将所有数据保存到 json 文件中,但只获取最后一个索引

mysql - 如何使用csv.Writer输出MySQL数据

interface - 了解界面