peaxol
peaxol

Reputation: 587

How to log a struct with a mutex

I have a struct in Go with a mutex:

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) 
}


Above gives a go vet warning (https://play.golang.org/p/J0NFgBvSGJC) :

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

I saw a related github issue https://github.com/golang/go/issues/13675 and understand the need of this warning in general to warn about copying locks. I can workaround above by creating a custom string method omitting the lock. However - since structs with mutexes seem widespread, I am wondering if there is a better/idiomatic way to log structs containing mutexes in Go?

Upvotes: 5

Views: 1487

Answers (1)

Grzegorz Żur
Grzegorz Żur

Reputation: 49231

You should not pass foo2 by value because you would copy the mutex. Mutex makes sense only if it is a shared as a pointer. Therefore pass the whole structure as a pointer.

fmt.Println(&foo2)

Or extend the formatting

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

Upvotes: 7

Related Questions