Use go run to compile and execute Go source files in a single step without creating a binary artifact, making it ideal for quick scripts, testing logic, or prototyping. It accepts one or more .go files (or a directory) and automatically resolves dependencies before running the main function.
For a single file, simply pass the filename directly. This works best for self-contained scripts where you don't need a persistent binary.
go run main.go
If your code is organized in a package within a directory, you can pass the directory path or the package import path. This allows go run to build the entire package, including all necessary files in that directory, before execution.
# Run all .go files in the current directory
go run ./cmd/myapp
# Or run using the import path relative to the module root
go run ./cmd/myapp/main.go
Keep in mind that go run is not intended for production deployment. It rebuilds the binary every time you execute the command, which is slower than running a pre-compiled binary (go build followed by ./myapp). Additionally, it only works with packages containing a main function; attempting to run a library package will result in an error.
When debugging, you can pass flags to the Go compiler or the program itself. Flags for the compiler (like -race for race detection) must come before the package path, while arguments for your program come after.
# Enable race detection during execution
go run -race ./cmd/myapp
# Pass arguments to the program (note the space after the package path)
go run ./cmd/myapp --config prod.yaml
For larger projects, prefer go build to create an optimized binary, then run that binary for better performance. Use go run strictly for development iterations where you need to see changes immediately without managing build artifacts.