Urgent.News

One page, thousands of outlets. See who else covered it.

Editions

Tech

How Go detects struct copies with sync.noCopy

Go's sync package includes a noCopy field used to prevent copying of certain structs after their first use. Despite noCopy being just an empty struct with two empty methods, it serves an important purpose. This post explains why noCopy is necessary, how it works, and how to add it to your own types. The noCopy marker isn't a special rule in Go's compiler; copying a value still works as expected.

However, go vet, a static analysis tool, can flag potential issues. It checks if a type implements the sync.Locker interface, which has two methods: Lock and Unlock. If a type doesn't implement sync.Locker, go vet flags it as a potential issue. This check applies recursively to nested structs. The noCopy methods (Lock and Unlock) exist for historical reasons, as they allow go vet to distinguish between types that can and cannot be safely copied.

This distinction is crucial for types like sync.Mutex, which contain internal state that must not be copied. Even though the noCopy marker doesn't prevent the compiler from copying a value, it does provide a way for tools like go vet to catch potential issues. The marker also helps make the copying restriction clearer in warning messages.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at func25.dev →

More in Tech

More from Monday 17 August →