Return an unexported type from a function

I would say there’s nothing wrong with returning an unexported variable from an exported function. That’s what an accessor is by definition.

That said, I would only do that in the case where there was some logic that needed to occur every time the unexported variable needed to be accessed.

EDIT:
I hope I understand your clarified question.

If you have an unexported type user struct{} and you return it with NewUser(), would that fit your use case? If so, then that is a factory design pattern and is useful in Go if you do not want a 3rd party developer to directly create a user type object. That way, your “constructor” or “factory” is the only place to get new instances.

So, is it “bad style”? I’d say it depends on what challenge needs to be overcome.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)