英文:
Go Global Variables and Scopes of slices
问题
我正在使用GO语言入门,遇到了一个我无法解决的错误。我该如何创建一个全局切片,使模块内的所有函数都可以使用它?以下是我的代码:
package main
import (
"fmt"
)
type Req struct {
Req int
Name string
}
var Reqs []Req
func ReadReqs(fp string) {
var CReq Req
CReq.Req = 1
CReq.Name = "first"
Reqs := append(Reqs, CReq)
}
func main() {
Reqs := make([]Req, 0)
if len(Reqs) > 0 {
fmt.Println(Reqs[0])
}
fmt.Println(Reqs)
}
这段代码无法编译,因为出现了以下错误:
./question.go:18: Reqs declared and not used
我原以为声明 var Reqs []Req
应该可以声明变量,但在 ReadReqs
函数内似乎没有意识到它。我知道全局变量是不好的,但我想在这个简单的程序中使用全局变量。
英文:
I am starting out with GO language, and getting an error I cannot figure out. How do I create a global slice that all functions within the module can use? Here is what I have:
package main
import (
"fmt"
)
type Req struct {
Req int
Name string
}
var Reqs []Req
func ReadReqs(fp string) {
var CReq Req;
CReq.Req = 1
CReq.Name = "first"
Reqs := append(Reqs, CReq)
}
func main() {
Reqs := make([]Req, 0)
if len(Reqs) > 0 {
fmt.Println(Reqs[0])
}
fmt.Println(Reqs)
}
This code will not compile because of the following error:
./question.go:18: Reqs declared and not used
I was thinking that declaring var Reqs []Req should declare the variable, but it does not seem to be aware of it inside the ReadReqs function. I do realize that globals are BAD but I would like to use global var for this simple program.
答案1
得分: 3
首先,我建议你在继续之前阅读《Effective Go》(http://golang.org/doc/effective_go.html)。
你使用以下方式声明全局变量:
var Reqs []Req
然后再使用相同的名称重新声明一个变量:
Reqs := ......
这样你就声明了两个不同的变量。
使用var Name type
也会初始化变量:
var s string
等同于:
s := ""
所以以下这行代码是多余的:
Reqs = make([]Req, 0)
你可以在Golang Play上尝试你修复后的代码。
英文:
Okay first of all I'd recommend you to read Effective Go before continuing.
You are declaring your global variable using:
var Reqs []Req
Then re-declaring a variable with the same name using:
Reqs := ......
You are declaring two different variables.
var Name type also initializes the variable:
var s string
Is equivalent to:
s := ""
So this makes the following line useless:
Reqs = make([]Req, 0)
You can try your fixed code here (Golang Play).
答案2
得分: 2
使用:=
,你声明了一个新的变量(而不是写入全局变量),这个新变量在函数作用域中未被使用(与全局变量无关)。
英文:
With :=
you are declaring a new variable (not writing to the global) and that new variable at function scope is unused. (Has nothing to do with globals.)
答案3
得分: 1
你正在使用:=
运算符重新声明Reqs
。去掉冒号。
你可能应该先从基础知识开始:
英文:
You're re-declaring Reqs
with the :=
operator. Drop the colon.
You should probably start with the basics first:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论