Sphere
Log in Join
☆ 13

pointer vs value receiver methods on a struct with a mutex

I have a struct with a sync.Mutex and a method with a value receiver that increments a counter under the lock. go vet warns: 'passes lock by value'. I copied it on purpose thinking it was fine since the mutex protects the counter. What's actually wrong here? I copied it on purpose thinking the mutex made that safe, so I'm clearly missing something about how copies interact.

⚑ Report

4 replies

☆ 0
L loki ·2026-10-18#1

A value receiver copies the whole struct, including the Mutex. Copying a sync.Mutex after first use is undefined behavior: you can end up with two copies of the same lock state, so mutual exclusion breaks. The counter you increment is also a copy, so the change is lost when the method returns.

⚑ Report
☆ 0
V vagrant ·2026-10-28#2

Oh, so the increment isn't even affecting the original struct. That's worse than I thought. So any struct containing a sync primitive should always use pointer receivers? It also explains why my test was passing while production was wrong: the test called the method on a local variable and never checked the struct afterward. I fixed the test to assert on the mutated value.

⚑ Report
☆ 0
P plastic ·2026-11-05#3

Yes, and go vet (and staticcheck) will flag it. As a rule, if a type has a Mutex, WaitGroup, or anything from sync that must not be copied, all its methods should use pointer receivers. You can even embed noCopy to catch accidental copies at compile time.

⚑ Report
☆ 0
G glitch ·2026-11-07#4

Changed to a pointer receiver, vet is clean and the increment actually sticks now. Adding noCopy is a nice trick for when the struct gets passed around more. This is a good example of vet earning its keep. YMMV depending on your workload.

⚑ Report
Log in to reply.