在Go中跨包访问变量 [英] Accessing variables across packages in Go

查看:484
本文介绍了在Go中跨包访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在package main范围内有两个变量,就是这些变量:

I have two variables in the scope of package main, those would be these:

var (
    app Application
    cfg Config
)

现在,由于我的应用程序的大小开始增加,因此我决定将网站的每个模块放在自己的程序包中,就像子目录一样:

Now, since the size of my application is starting to increase, I have decided to put each module of the website in its own package, much like a subdirectory as so:

/src/github.com/Adel92/Sophie
  + user/   (package user)
     - register.go
     - login.go
     - password.go
  + topic/  (package topic)
     - ... etc
  - main.go (package main)

我该如何解决从其他软件包访问appcfg全局变量的问题?这是错误的方法吗?我有一种感觉.

How would I go around around accessing the app and cfg global variables from other packages? Is this the wrong way to go about it? I have a feeling it is.

在那种情况下,我将如何在其自己的命名空间中声明函数,这样我就不必一直为usertopic所附加的名称而发疯.

In that case, how would I declare functions in their own namespace so I don't have to go crazy with names that are affixed with user and topic all the time.

推荐答案

大写的变量名被导出以在其他程序包中访问,因此AppCfg将起作用.但是,通常不建议使用子包进行名称间隔.软件包旨在用于离散的独立功能,因此通常比使用这种方法要麻烦的多(例如,导入周期是绝对不可能的,因此,如果在此布局中有两个子软件包需要与之通信彼此,那么你就不走运了.

Capitalized variable names are exported for access in other packages, so App and Cfg would work. However, using sub-packages for name-spacing is generally not recommended; packages are intended for discrete, self-contained functionality so it is usually more trouble than it's worth to use them this way (for example, import cycles are strictly impossible, so if you have two sub-packages in this layout that need to talk to each other then you're out of luck).

如果发现需要为事物加上前缀usertopic以避免名称冲突,则可能应将基础概念纳入其自己的程序包中,并且可以为它创建一个实例user和一个topic?

If you're finding you need to prefix things with user and topic in order to avoid name collisions, then perhaps the underlying concept should be factored into its own package, and you can create one instance of it for user and one for topic?

这篇关于在Go中跨包访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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