从函数返回未导出的类型 [英] Return an unexported type from a function

查看:54
本文介绍了从函数返回未导出的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从导出的函数返回未导出的类型是否被认为是不好的风格?
使用它后,我通常会发现它只会带来问题.

Is it considered bad style to return an unexported type from an exported function?
When I've used it, I mostly find it just creates problems.

一个更好的问题可能是:什么时候从导出的函数返回未导出的类型是个好主意.

A better question might be: when is it a good idea to return an unexported type from an exported 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.

希望我能理解您提出的问题.

I hope I understand your clarified question.

如果您有未导出的类型用户struct {} ,并且使用 NewUser()返回它,那么这是否适合您的用例?如果是这样,那么这是一种工厂设计模式,如果您不希望第三方开发人员直接创建 user 类型的对象,则在Go中很有用.这样,您的构造函数"或工厂"是获取新实例的唯一位置.

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.

这篇关于从函数返回未导出的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆