
Dancing with Go's Mutexes - WestCoastJustin
https://medium.com/@deckarep/dancing-with-go-s-mutexes-92407ae927bf
======
AYBABTME
Just a cursory reading, but I noticed the author embeds the mutex in their
structs. I'd recommend against doing that by default, because that mutex's
methods become part of your API. Maybe in some cases you desire that, but I
argue that in most case you don't.

The fact that your struct be concurrency-safe through mutex is an
implementation detail. You want to keep the locking/unlocking internal to your
type, you don't want to expose it to outsiders. Exporting the methods of the
mutex in your struct suggests that somehow, it's ok for users of the type to
lock/unlock it. I doubt that this is true. In practice, if your struct is
"concurrency-safe", it means using its methods is sufficient to obtain a safe
behavior. If a user of the type never requires access to the mutex, don't
export it. Especially since mutexes aren't reentrant, in most case if a user
of your struct attempted to Lock the struct before calling a method, they'd
deadlock themselves.

TL;DR: for API design reasons, don't embed a mutex in your struct.

~~~
LukeShu
Because others might not be up with the terminology: in a Go struct an
"embedded field" or "anonymous field" is a member of a struct that you didn't
give a name to.

    
    
        type MyType struct {
            sync.Mutex    // embedded/anonymous
            mu sync.Mutex // not embedded
        }
    

So AYBABTME's advice is to give the mutex a name.

