简体   繁体   English

Go 项目中的多个主要文件

[英]Mutiple main files in Go project

I have a Go project.我有一个围棋项目。 When I run the program main.go (with function main ), it serves a web server serving a JSON object.当我运行程序main.go (带有main函数)时,它会为一个 Web 服务器提供一个 JSON 对象。

In the same folder I have another file serializedata.go (with function main ) which writes the JSON object into a file that is served by the web server.在同一个文件夹中,我有另一个文件serializedata.go (带有main函数),它将 JSON 对象写入由 Web 服务器提供的文件中。

Now, when I try to run go install I get this error:现在,当我尝试运行go install时,出现此错误:

./serialize_data.go:17: main redeclared in this block previous declaration at ./main.go:13 ./serialize_data.go:17: main 在此块中重新声明,之前在 ./main.go:13 处声明

I want to keep both these files together as they are related.我想将这两个文件放在一起,因为它们是相关的。 The test data needs to be serialized before it can be served.测试数据需要序列化后才能提供服务。

How can I prevent to build the serialization.go file?如何防止构建serialization.go文件?

I'm from python world and there it's easy to have these utils files separately.我来自 python 世界,很容易分别拥有这些 utils 文件。

serialize_data.go 应该放在另一个文件夹中,然后go run serialize_data.go

Create a file in main package named serialization.go .在主包中创建一个名为serialization.go的文件。 but change the name of the function main with the any exported function with upper case letter and then call it inside the main.go file.但是使用任何带有大写字母的exported函数更改函数 main 的名称,然后在main.go文件中调用它。 Each package can have only a single main file.每个包只能有一个主文件。 So if you want to create a file with main() function inside it declare in another package.因此,如果您想创建一个包含main()函数的文件,请在另一个包中声明。

For eg your main.go should looks like.例如,您的main.go应该看起来像。

package main

func main(){
    Serialize()
}

Inside serialization.go file use asserialization.go文件中用作

package main

func Serialize(){
   fmt.Println("Serialize")
}

Call above function inside main for serving on web browser在 main 中调用上述函数以在 Web 浏览器上提供服务

While not nessarily a good idea, if you avoid go install you can build several executables from the same folder just fine.虽然这不是一个好主意,但如果您避免使用go install您可以从同一个文件夹中构建多个可执行文件就好了。 One of my projects has a tools folder with several executables, that I build using go build .我的一个项目有一个包含多个可执行文件的tools文件夹,我使用go build Eg:例如:

$ ls
Makefile cat.go find.go ls.go
$ cat Makefile
%: %.go
    go build -o $@ $<
$ make ls
go build -o ls ls.go
$ ./ls
Makefile cat.go find.go ls.go

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM