Returning an unexported type from a function

Is it considered incorrect to return an unexported type from an exported function?
When I used it, I basically think that it just creates problems.

A better question might be: when is a good idea to return an unexported type from an exported function.

+16
go
source share
3 answers

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

However, I will only do this if there is some logic that should occur every time you need to access an unexported variable.

EDIT: I hope I understand your clarified question.

If you have an unexported type user struct{} and you return it using NewUser() , is this suitable for your use case? If so, then this is a factory design pattern that is useful in Go if you do not want a third-party developer to directly create a user object of type. Thus, your "constructor" or "factory" is the only place where you can get new instances.

So is this a "bad style"? I would say that it depends on what problem needs to be overcome.

+10
source share

Golang linters return a warning when you return an unexported type, so I would say, although it is technically possible that this is also not recommended. one

One of the reasons is that some code that receives an unexported type cannot save it (iirc without going to interface{} ).

eg:

 package me type me string func NewMe() me { return "me" } // in main.go package main type eff struct { m *me.me // <-- cant do this } 
+2
source share

As @Brenden explained, this can be good practice when some “attributes” remain “private”.

I use the words, constructor and private event attributes, although Go does not support real OOP, but here the goal is to emulate some OOP functions.

One way to achieve this without linter claims is to use the exported structure to encapsulate an unexported type. But then you need a “constructor”, because you cannot create an unexported type somewhere else.

Example:

A counter that can only increase. So you want to hide the meaning and keep it secret.

 package counter type Counter struct { inner counter } type counter struct { value int } func New() Counter { return Counter{counter{0}} } func (obj *Counter) Increment() { obj.inner.value++ } func (obj Counter) Value() int { return obj.inner.value } 
0
source share

All Articles