-1

When I use flag package

// main.go

import (
  ...
  "flag"  
)

func main() {
  ...
  flag.Parse()

  switch flag.Arg(0) {
  case "doSomething1":
    ...
  case "doSomething2":
    ...
  }

}

If doSomething1 argument print some error message for me, whatever I fix the source code, it can not remove the old error code and compile again.

// command-line

# go build ./main.go
# ./main doSomething1
# error doSomething1 can not work

-- I fix my code

# ./main doSomething1
# error doSomething1 can not work

-- the error message also show me again
-- I have to delete main and build again

# rm ./main
# go build ./main.go
# ./main.go doSomething1
# doSomething1 now can work
ccd
  • 5,788
  • 10
  • 46
  • 96
  • If you don't rebuild, you're calling the binary built with the old code. Changing source has no impact on the binary until you rebuild it. – Adrian Nov 05 '19 at 15:03

1 Answers1

5

Go is a compiled language. When you run go build, it will compile your sources and create an executable binary. This is what you run when executing ./main doSomething1.

When you change your sources and run ./main doSomething1, you are not compiling again, you just run the previously built (and unchanged) binary.

To quickly test changes, use go run instead:

go run main.go doSomething1

That will always compile your sources, build a binary in a temporary folder, launch it and clear it once your app exits.

For details, see What does go build build?

icza
  • 389,944
  • 63
  • 907
  • 827