1 min read

Managing multiple Go programs with main functions in a single folder

When you have multiple Go files in the same folder, each containing a main function, you'll encounter a problem when trying to build or run your program. Go treats all files in the same folder as part of the same package, and having multiple main functions in a single package will result in a compile-time error.

To resolve this issue, you can:

  1. Create separate folders for each Go file with a main function:
- root_directory
  - program1
    - main.go
  - program2
    - main.go

2.  Use build constraints (build tags) to selectively compile only one main function at a time:

In each Go file with a main function, add a build constraint as a comment at the top of the file. For example:

main1.go:

//go:build main1

package main

import "fmt"

func main() {
    fmt.Println("Hello from main1!")
}

main2.go:

//go:build main2

package main

import "fmt"

func main() {
    fmt.Println("Hello from main2!")
}

Now, when you want to build or run one of these files, you can use the -tags flag followed by the build constraint:

$ go run -tags main1 main1.go
Hello from main1!

$ go run -tags main2 main2.go
Hello from main2!