Golang全局结构体初始化

huangapple go评论117阅读模式
英文:

golang global struct initialization

问题

我想声明一个属于特定包的全局结构体变量并对其进行初始化。

我有以下的目录结构:

  1. main
  2. ├── symbol
  3. | ├── symbol.go
  4. | └── Comma.go
  5. ├── main.go
  6. └── go.mod

symbol.go:

  1. package symbol
  2. type Symbol struct{
  3. Name string
  4. Format string
  5. }

Comma.go:

  1. package symbol
  2. var Comma = Symbol{}
  3. Comma.Name = "Comma"
  4. Comma.Format = ","

main.go:

  1. package main
  2. import "fmt"
  3. import "github.com/.../symbol"
  4. func main() {
  5. s := symbol.Comma
  6. fmt.Println(s.Name)
  7. }

当我运行这个程序时,它显示以下错误信息:
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:

  1. main
  2. ├── symbol
  3. | ├── symbol.go
  4. | └── Comma.go
  5. ├── main.go
  6. └── go.mod

symbol.go:

  1. package symbol
  2. type Symbol struct{
  3. Name string
  4. Format string
  5. }

Comma.go:

  1. package symbol
  2. var Comma = Symbol{}
  3. Comma.Name = "Comma"
  4. Comma.Format = ","

main.go:

  1. package main
  2. import "fmt"
  3. import "github.com/.../symbol"
  4. func main() {
  5. s := symbol.Comma
  6. fmt.Println(s.Name)
  7. }

When I run this, it says: <br>
syntax error: non-declaration statement outside function body

How can I fix this ?

答案1

得分: 4

声明语句是唯一允许在包级别的语句类型。下面的语句是赋值语句:

  1. Comma.Name = "Comma"
  2. Comma.Format = ","

赋值语句不是声明语句。

有两种方法可以解决这个问题。第一种也是首选的方法是在变量声明中使用复合字面量初始化值。

  1. var Comma = Symbol{Name: "Comma", Format: ","}

第二种方法是将赋值语句移到一个init函数中:

  1. func init() {
  2. Comma.Name = "Comma"
  3. Comma.Format = ","
  4. }

init函数在包初始化时自动执行。

英文:

Declaration statements are the only statement type allowed at package-level. The statements

  1. Comma.Name = &quot;Comma&quot;
  2. Comma.Format = &quot;,&quot;

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.

  1. var Comma = Symbol{Name: &quot;Comma&quot;, Format: &quot;,&quot;}

The second way is to move the assignment statements to an init function:

  1. func init() {
  2. Comma.Name = &quot;Comma&quot;
  3. Comma.Format = &quot;,&quot;
  4. }

init functions are automatically executed when the package is initialized.

答案2

得分: 2

使用复合字面量:

  1. var Comma = Symbol{Name: "Comma", Format: ","}

Go编程语言规范:复合字面量

英文:

Use a composite literal:

  1. var Comma = Symbol{Name: &quot;Comma&quot;, Format: &quot;,&quot;}

The Go Programming Language Specification: Composite literals

huangapple
  • 本文由 发表于 2023年2月26日 09:28:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75569489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定