如何使用互斥量记录结构

How to log a struct with a mutex

我在 Go 中有一个带有互斥锁的结构:

package main

import (
    "fmt"
    "sync"
)

type foo struct {
    sync.Mutex
    lastID       uint64
    nameToID map[string]uint64
}

func main() {
    fmt.Println("Hello, playground")
    foo2 := foo{lastID: 0,nameToID: map[string]uint64{"name":0}}
    fmt.Println(foo2) 
}


上面给出了兽医警告(https://play.golang.org/p/J0NFgBvSGJC):

./prog.go:17:14: call of fmt.Println copies lock value: play.foo

我看到了一个相关的 github 问题 https://github.com/golang/go/issues/13675 并理解这个警告的必要性,以警告复制锁。 我可以通过创建一个省略锁的自定义字符串方法来解决上面的问题。 但是 - 由于带有互斥锁的结构似乎很普遍,我想知道是否有 better/idiomatic 方法来记录 Go 中包含互斥锁的结构?

只需使用指针

fmt.Println(&foo2)

或扩展格式

fmt.Printf("%+v\n", &foo2)