全局变量专用于文件 [英] Global variable private to file

查看:83
本文介绍了全局变量专用于文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在GOLANG中,有没有一种方法可以使变量的作用域局部于包中的文件? 就我而言,有2个文件ex1.go和ex02.go. ex01.go定义了一个全局变量

In GOLANG, Is there a way to make a variable's scope local to a file within a package? In my case, there are 2 files ex1.go and ex02.go. ex01.go defines a global variable

var wg sync.WaitGroup

在该文件中的所有函数中使用.

which is used across functions in that file.

在另一个文件ex02.go中(与ex01.go无关,除了ex01.go和ex02.go属于同一类问题,即并发),我无法为waitGroup定义一个变量,如下所示:

In another file ex02.go (which has no relation with ex01.go except that both ex01.go and ex02.go belong to the same class of problems - i.e. concurrency), I can't define a variable for waitGroup as

var wg sync.WaitGroup

我得到一个错误-在此块中重新声明了变量名"

I get an error - "variable name is re-declared in this block"

有没有一种方法可以防止变量名溢出到其他文件中?

Is there a way to keep the variable names from spilling over to the other files?

推荐答案

出于变量作用域的目的,文件在Go中没有任何意义.可以将包中的所有文件都看作是串联在一起的,这(简化的)正是编译之前发生的情况.

For the purpose of variable scoping, files have no meaning in Go. Think of all files in a package as if they would be concatenated, which (simplified) is exactly what happens before compilation.

这意味着:不,无法将变量限定范围到文件.

That means: No, there is no way of scoping a variable to a file.

如果需要两个全局WaitGroup,则需要将它们定义为单个变量.

If you need two global WaitGroups, you need to define them as individual variables.

这篇关于全局变量专用于文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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