Your first program
Create a file namedmain.go and add the following code:
Understanding the structure
Package declaration
main package is special - it tells Go this is an executable program, not a library.Import statement
import keyword brings in code from other packages. Here, fmt (short for “format”) provides functions for formatted I/O, including printing to the console.Running your program
Go provides two ways to execute your code:Quick execution with go run
Building an executable with go build
main.exe. On macOS or Linux, you’ll get a file named after your directory or main.
You can then run the executable directly:
Compiled Go programs are completely standalone. You can copy the executable to another computer (with the same OS and architecture) and run it without installing Go.
How compilation works
Understanding Go’s compilation process helps you appreciate its speed and simplicity:- Source code: You write human-readable Go code
- Compiler: The Go compiler translates your code into machine code
- Executable: A binary file your computer can run directly
- Output: Your program runs and displays the result
Why package main?
Go needs to distinguish between two types of code:
- Applications: Programs you can run (use
package main) - Libraries: Code that other programs can use (use any other package name)
Unlike scripting languages like Python or JavaScript, Go requires this explicit distinction. This prevents common mistakes like accidentally trying to run library code or importing application code as a library.
Common mistakes
Experiment
Try these modifications to understand how the program works:-
Change the message to print your name:
-
Add multiple print statements:
-
Try using
fmt.Printinstead offmt.Printlnand observe the difference
Key takeaways
- Every Go program starts with a package declaration
- The
mainpackage andmain()function mark an executable program importbrings in code from other packagesgo runquickly compiles and executes your codego buildcreates a standalone executable- Go is a compiled language that produces fast, standalone binaries