英文:
golang global struct initialization
问题
我想声明一个属于特定包的全局结构体变量并对其进行初始化。
我有以下的目录结构:
main
├── symbol
| ├── symbol.go
| └── Comma.go
├── main.go
└── go.mod
symbol.go:
package symbol
type Symbol struct{
Name string
Format string
}
Comma.go:
package symbol
var Comma = Symbol{}
Comma.Name = "Comma"
Comma.Format = ","
main.go:
package main
import "fmt"
import "github.com/.../symbol"
func main() {
s := symbol.Comma
fmt.Println(s.Name)
}
当我运行这个程序时,它显示以下错误信息:
syntax error: non-declaration statement outside function body
我该如何修复这个问题?
英文:
I want to declare a global struct variable which belongs to a certain package and initialize it.
I have a following directory structure:
main
├── symbol
| ├── symbol.go
| └── Comma.go
├── main.go
└── go.mod
symbol.go:
package symbol
type Symbol struct{
Name string
Format string
}
Comma.go:
package symbol
var Comma = Symbol{}
Comma.Name = "Comma"
Comma.Format = ","
main.go:
package main
import "fmt"
import "github.com/.../symbol"
func main() {
s := symbol.Comma
fmt.Println(s.Name)
}
When I run this, it says: <br>
syntax error: non-declaration statement outside function body
How can I fix this ?
答案1
得分: 4
声明语句是唯一允许在包级别的语句类型。下面的语句是赋值语句:
Comma.Name = "Comma"
Comma.Format = ","
赋值语句不是声明语句。
有两种方法可以解决这个问题。第一种也是首选的方法是在变量声明中使用复合字面量初始化值。
var Comma = Symbol{Name: "Comma", Format: ","}
第二种方法是将赋值语句移到一个init
函数中:
func init() {
Comma.Name = "Comma"
Comma.Format = ","
}
init
函数在包初始化时自动执行。
英文:
Declaration statements are the only statement type allowed at package-level. The statements
Comma.Name = "Comma"
Comma.Format = ","
are assignment statements. Assigments are not declarations.
There are two ways to fix the problem. The first and preferred way is to initialize the value in the variable declaration using a composite literal.
var Comma = Symbol{Name: "Comma", Format: ","}
The second way is to move the assignment statements to an init
function:
func init() {
Comma.Name = "Comma"
Comma.Format = ","
}
init
functions are automatically executed when the package is initialized.
答案2
得分: 2
使用复合字面量:
var Comma = Symbol{Name: "Comma", Format: ","}
英文:
Use a composite literal:
var Comma = Symbol{Name: "Comma", Format: ","}
The Go Programming Language Specification: Composite literals
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论