Go:无法初始化结构体

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

Go: Unable to initialize struct

问题

我无法初始化一个结构体,即使它没有显示任何linting错误,但在编译时会抛出错误。

错误信息如下:

$ go run main.go 
# command-line-arguments
.\main.go:19:10: undefined: Application

这是结构体的定义:


/* app.go */

type Application struct {

	config struct {
		port string      // 从命令行标志读取
		env string       // 从命令行标志读取
		api string       // 从命令行标志读取

		stripe struct {
			secret string  // 从环境变量读取
			key string     // 从环境变量读取
		}

	} 

	infoLog   *log.Logger
	errorLog  *log.Logger 
	templateCache map[string]*template.Template
	version   string 

	DB *sql.DB
	Router *mux.Router

}

这是我如何初始化它的方式:


/* main.go */

app := Application{}

完整的代码在这里

非常感谢您的帮助!谢谢!

英文:

I am unable to initialize a struct, even though it does not show any linting error, it throws error while compiling

<h3>Error</h3>

$ go run main.go 
# command-line-arguments
.\main.go:19:10: undefined: Application

Here's the struct:


/* app.go */

type Application struct {

	config struct {
		port string      // to be read from the command line flag 
		env string       // to be read from the command line flag 
		api string       // to be read from the command line flag 

		stripe struct {
			secret string  // to be read from the environment variable 
			key string     // to be read from the environment variable
		}

	} 

	infoLog   *log.Logger
	errorLog  *log.Logger 
	templateCache map[string]*template.Template
	version   string 

	DB *sql.DB
	Router *mux.Router

}

And here's how I am initializing it:


/* main.go */

app := Application{}

The code full code is here

Would really appreciate the help, thanks!

答案1

得分: 1

尝试运行go run .(这里你传递的是文件夹而不是文件)或者go run main.go app.go routes.go

如果你只运行go run main.go,它只会加载main.go,而main.go没有直接引用其他文件中定义的结构体,所以找不到。通过传递包含所有主要文件的文件夹或显式地传递所有文件,就不会有混淆。

英文:

Try running go run . (here you're passing the folder instead of the files) or go run main.go app.go routes.go.

If you just run go run main.go it'll only load main.go which doesn't have any direct reference to the other files so it can't find the struct defined in the other files. By passing the folder containing all the main package files or passing all of the files explicitly then there's no confusion.

huangapple
  • 本文由 发表于 2021年9月11日 04:40:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/69137809.html
匿名

发表评论

匿名网友

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

确定