I'm trying to figure out a way to best signal to other developers maintaining a single package that a field is unsafe to access directly. In this case, it's being lazily loaded, and the only way to ensure it will be properly loaded is to access the method wrapper rather than directly accessing the field.
// Method wrapper that does lazy-loading
func (f *foo) getBar() string {
// lazy-load this from a database or some other expensive call
fmt.Printf("f.bar directly: %v\n", f.bar)
fmt.Printf("f.bar lazy-loaded: %v\n", f.getBar())
If you access the field directly, you get an empty value. If you call the method wrapper, you get the intended value.
I believe the official answer is just "do the right thing" since you are within the package boundaries and have full control. And I'm pretty sure the language doesn't provide anything here.
But what I'm wondering -- are there any common conventions or workarounds to avoid this pitfall? So far the only idea I've been able to come up with is to use underscores and/or comments to clearly mark the field as being unsafe to access directly:
_bar string // You probably want to use getBar() since this is lazily loaded an unsafe to access directly.