Golang全局结构体初始化

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

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 = &quot;Comma&quot;
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.

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

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

func init() {
	Comma.Name = &quot;Comma&quot;
	Comma.Format = &quot;,&quot;
}

init functions are automatically executed when the package is initialized.

答案2

得分: 2

使用复合字面量:

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

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

英文:

Use a composite literal:

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:

确定