Running your first Go program
Creating Your Go Program
Is time to write your first Go program. Open your favourite editor I will be using VS code. After that Create a new file called main.go
with the following code.
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
Let’s break down this code.
In Go, every file is part of a package, and this is specified at the beginning of the file with the package
keyword. A package is a collection of related functions and files.
package main
: main
is a special name that tells Go this is the entry point of the program.
func main()
It’s the first function that gets executed. If you skip the func main()
in the main
package you will get the following error when trying to run the program.
program runtime.main_main·f: function main is undeclared in the main package
import "fmt"
: This line includes the fmt
package. The fmt
package provides functions for formatted input and output, like printing text.
fmt.Println("Hello, World!")
: This line outputs the string Hello, World!
to the console.
If you want a function to be accessible from other packages, its name must start with a capital letter. This rule applies to any item you want to export, making it available to other packages.
Running the Program
To run the program:
- Open a terminal in VS Code by selecting Terminal > New Terminal from the menu.
- Run the command
go run main.go
in the terminal. You should see the output “Hello, Go!” in the terminal.
Compiling the Program
To compile the program into an executable:
In the terminal, type the command go build main.go
. This command creates an executable file named main
in the same directory.
Compiling your Go program into an executable makes it easy to run on any computer without Go installed.
To run your compiled executable:
- On Unix-based systems (like Linux or macOS), type
./main
in the terminal and press Enter. - On Windows systems, type
main.exe
and press Enter.
Conclusion
Full source code can be found here Github
By following these steps, you’ve created and run your first simple Go program and compiled it into an executable file. See you in the next tutorial where you will learn about variables & types.