golang global structure initialization

WBOY
Release: 2024-02-12 09:33:08
forward
1260 people have browsed it

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
Copy after login

symbol.go

package symbol

type symbol struct{
    name string
    format string
}
Copy after login

comma.go

package symbol

var comma = symbol{}

comma.name = "comma"
comma.format = ","
Copy after login

main.go

package main
import "fmt"
import "github.com/.../symbol"

func main() {
    s := symbol.Comma
    fmt.Println(s.Name)
}
Copy after login

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 = ","
Copy after login

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: ","}
Copy after login

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

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!