in a real project I would create just one main.go, but now I’m learning go with many hands-on coding so I’d like to know if I can create multiple main.go under different folders so it’s convenient for me to learn all codings in one place?
in a real project, can I create multiple main.go files?
what’s the best practice?
Of course you can’t give them the same name when you put them in the same folder, but you can name them differently, as long as the all have a package main and a main() function.
Yes different file name is allowed as long as they are under the same package. I guess i didn’t got the question right, i think he asked about two main.go files in same folder (same name)
… sorry
Thanks for all the reply and sorry for my late response - busy with my daytime work.
I tried to create two go files under same folder, each file has package main and func main(),
in this folder, when I run go build, I get some complain like
(base) zwang-mac:cmd1 zwang$ go build
# _/Users/zwang/GolandProjects/learngo/cmd/cmd1
./race.go:14:6: main redeclared in this block
previous declaration at ./main.go:10:6
and it dosen’t create any binary file. But when I do go build for each go file, like
go build main.go
go build race.go
it does generate binary files for each successfully. so I think my question is why go complains the go build without specifying the go file in this case
The reason is that when there is no filename provided to go build, it treats the given command as building the package (go build .). The compiler can see both main.go and race.go at the same time and, it does not know which func main() you prefer to use. Hence, it said one of them is re-declared.
Go allows single script build which is why you can build each of them independently. However, it does not include dependencies so when you do that.
In practice, it is one folder for one package main with one func main(). You can create as many main folders as you want in a repository.
The idea is to keep the main packages as simple and clean as possible while having your functions and library codes in the repository. This way, your repo is still importable by any cmd main codes and externally.
package pkg1
func Addition(a int, b int) int{
return a + b
}
under cmd/cmd2, I executed go build main.go, it generated binary file ‘main’, and when I run it it does print 5 as expected, so I think with go build main.go it looks like also include the dependence (which is the addition.go under pkg/pkg1 in this cae). is that right?