Let's Write Some Code!
With your Go development environment now set up, it's time for the moment we've been waiting for: writing our first lines of code.
In the world of programming, the "Hello, World!" program is a time-honored tradition. It's a simple program that prints a message to the screen, serving two main purposes:
- Confirming that our setup works correctly.
- Introducing us to the most basic syntax of a language.
Let's get started.
Step 1: Create Your Go File
Inside the project folder you created (e.g., my-go-project
), create a new file and name it main.go
.
All your Go code will live inside files with the .go
extension.
Step 2: Write the Code
Open your new main.go
file in your editor (VS Code or GoLand) and type the following code exactly as it is shown:
package main
import "fmt"
// This is the main function, the entry point of our program
func main() {
fmt.Println("Hello, World from Go!")
}
Step 3: Breaking Down the Code
It's a short program, but every line has an important role. Let's break it down so you understand what's happening.
package main
: This line declares that our file belongs to themain
package. In Go, an executable program (one you can run directly) must have amain
package.import "fmt"
: We are "importing" a built-in Go package namedfmt
(short for format). This package provides us with functions for formatting and printing text, much likeconsole.log
in JavaScript.func main()
: This defines themain
function. This function is special. It's the special entry point of our application. When we run the program, Go looks for func main() and executes the code inside it first. When we run the program, the code inside the curly braces{}
offunc main()
is the first code that gets executed.fmt.Println("Hello, World from Go!")
: Here we are calling thePrintln
(Print Line) function from thefmt
package we imported. This function prints the text"Hello, World from Go!"
to our terminal, and then adds a new line at the end.
Step 4: Running Your Program
Now for the magic. Return to your terminal, make sure you are still inside your project directory, and run the following command:
go run main.go
If everything was typed correctly, you will see this output on your screen:
Hello, World from Go!
Conclusion
Congratulations! You have just written, understood, and run your very first Go program. This is a fundamental and exciting milestone in learning any new language.
Top comments (0)