Home > Enterprise >  Go file not running which is not in main package
Go file not running which is not in main package

Time:04-29

I have a very simple Go project setup. At root directory I have go.mod file and main.go and a folder called main2. Inside main2 folder there is main2.go file.

/
|_ go.mod
|_ main.go
|_ main2
   |_ main2.go

From root directory I am trying to run go run command

go run main2/main2.go

and it throws error:

package command-line-arguments is not a main package

Can someone help?

CodePudding user response:

The package of your main2.go file must be main. When there is a main package, and a function main in your project, the compiler knows it will be compiled as a executable, and not as a library.

So try to change package command-line-arguments to package main inside the main2/main2.go file.

CodePudding user response:

Golang's entry point into an executable is through a single main() function. If you want to run different logic paths for a single executable, you can use main() as a routing function to the other packages using command line arguments:

package main

import (
    "os"
    // Your child packages get imported here.
)

func main() {

    // The first argument
    // is always program name
    // So os.Args[1] is the first dynamic argument
    arg1 := os.Args[1]

    // use arg1 to decide which packages to call
    if arg1 == "option1" {
        // option1 code executes here.
    }
    if arg1 == "option2" {
        // option2 code executes here.
    }
}

Then you can run your program with something like:

go run main.go option1

From golang documentation:

Program execution A complete program is created by linking a single, unimported package called the main package with all the packages it imports, transitively. The main package must have package name main and declare a function main that takes no arguments and returns no value.

  • Related