Home >Backend Development >Golang >golang global structure initialization

golang global structure initialization

WBOY
WBOYforward
2024-02-12 09:33:081305browse

golang global structure initialization

php editor Strawberry will introduce to you the global structure initialization in Golang today. In Golang, you can use structures to organize and manage data, and global structure initialization is a convenient and commonly used way. Through global structure initialization, we can initialize the structure when the program starts, avoiding the trouble of manual initialization every time the structure is used. Below we will introduce in detail the specific methods and precautions for global structure initialization to help everyone better understand and use this function.

Question content

I want to declare a global structure variable belonging to a certain package and initialize it.

I have the 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 it it says:

syntax error: non-declaration statement outside function body

How can I solve this problem?

Solution

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

comma.name = "comma"
comma.format = ","

is an assignment statement. Assignment is not a declaration.

There are two ways to solve this problem. The first and preferred method is to use compound literals to initialize the value in the variable declaration.

var comma = symbol{name: "comma", format: ","}

The second method is to move the assignment statement to the init function:

func init() {
    Comma.Name = "Comma"
    Comma.Format = ","
}

init The function is automatically executed when the package is initialized.

The above is the detailed content of golang global structure initialization. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete