Do not use go run main.go anymore
why not use go run main.go
How to run Golang programs
Why not use go run main.go
?
You should be thinking about it. I’m using go run main.go
to run my Golang programs,
and why I should not use it?
Well the explanation is quite simple!
Let’s create a file called main.go
:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Run it with go run main.go
and we should have a message:
Hello, World!
That’s it.
But
We always have a but, right!
If we have two files:
the one with main.go
and another with hello.go:
package main
import "fmt"
func main() {
run()
}
package main
import "fmt"
func run() {
fmt.Println("Hello, World!")
}
Trying to run go run main.go
will throw an error.
That’s because go run only runs the file with main.go
in it.
To fix this, we need to use go run .
after creating the go.mod
file.
Or we can use go run main.go hello.go
to run the file with hello.go
in it.
go mod init
go run .
Fix
To run this structure properly, we need to use go run .
This means that we will run the main function that it’s in the current directory.
Summary
- Why not use
go run main.go
? - But we always have a but, right!
- Fix