Home > OS >  How to call function in Go file from command line
How to call function in Go file from command line

Time:10-28

I have 2 go files:

main.go
otherFile.go

Inside of 'main.go' I have a 'main' function and I can call it from the command line like this:

go run main.go

So far so good.

Inside of 'otherFile' I can't have another 'main' function so I have a function called 'otherFunction'.

How can I call this function in 'otherFile.go' from the command line, similarly to how I did 'go run main.go'?

I don't necessarily want main.go to run, or call 'otherFunction' from 'main.go' by importing it, etc.

Is this possible or am I thinking about it in the wrong way? I am new to Go so still trying to figure out some of the basic concepts.

Thanks.

CodePudding user response:

You should be able to do what you want, if you structure your project along these lines:

  • /path/to/project/root/
    • apps/
      • an-app/
        • main.go
      • another-app/
        • main.go
    • package1/
    • package2/
    • package3/
    • . . .

where apps/an-app and apps/another-app are your commands that you want to run, and package1, package2, and package3 are shared packages that are imported by the apps.

CodePudding user response:

in the otherFile.go define a different package name. like:

package otherFile

Add the main() func, then run the function you want inside that main() func. From the terminal, you run go run otherFile.go.

The package system is different from what other languages have. But you'll get the idea if you keep using them.

  •  Tags:  
  • go
  • Related