-1

I have a go server which I normally run like this:

go build . && ./main

But online I see many examples using go run . which is better to use and what is the difference?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186

1 Answers1

2

From official documentation (go1.11):

go run - compiles and runs the named main Go package.

go build - compiles the packages named by the import paths, along with their dependencies, but it does not install the results.

go install - compiles and installs the packages named by the import paths.

It means:

Usually for LOCAL environment it's ok to use go run,
but for PROD environment it's better to build your app with go build and run ./main,
but in case you need Go toolchain you must use go install because it installs packages and dependencies and run ./bin/main (it may make sense in dev/stage environment).

cn007b
  • 16,596
  • 7
  • 59
  • 74
  • so go install and then ./main ? – CommonSenseCode Mar 14 '19 at 06:05
  • 1
    @CommonSenseCode, `go install` isn't likely to create `./main`. Pay close attention to what each command does. Now with modules and GOCACHE, there's very little difference between `build` and `install` aside from the final build artifact. – JimB Mar 14 '19 at 13:18
  • `go install` isn't about dependencies, it builds and puts the binary at `$GOPATH/bin`. `go install && go build` is unnecessary - it just produces two binaries at two different paths. And using `go run` in a dev environment is a very strange choice - I would only ever use `go run` locally, and generally not even then. – Adrian Mar 14 '19 at 14:42
  • If you want a step to install dependencies, that would be `go get`. – Adrian Mar 14 '19 at 14:43
  • @JimB `go install` isn't likely to create `./main`, `go install` creates `./bin/main` in $GOPATH. – cn007b Mar 14 '19 at 15:50
  • For prod it's probably best to `go build` elsewhere and just upload the binary somewhere and run it. There's no reason you should need to install the Go toolchain or run `go install` in production. – Adrian Mar 14 '19 at 15:54
  • @Adrian I'd written `go install && go build` just to have `main` ring on the place to run `./main`, but yes, you're right it's redundant, so I've updated my answer. Regarding DEV env - my mistake I meant exactly local environment. Thank you! – cn007b Mar 14 '19 at 15:55