In this tutorial, we will walk through the process of creating your first program in Go, a powerful and efficient language developed by Google.
By the end of the tutorial, you will know how to:
* Write a simple program in Go
* Compile your Go code
* Run your Go program
Before starting this tutorial, you should have Go installed on your computer. If you haven't, you can download it from the official Go website.
Go source files end with a .go
extension. Create a new file, hello_world.go
, and open it in your favorite text editor.
A Go program starts running in a package called main
. The fmt
package, which stands for format, provides functions for formatted I/O.
Here is how your hello_world.go
file should look like:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Once you've written your program, save the file. Then, open a new terminal window, navigate to the directory where your hello_world.go
file is located, and compile it using the go build
command:
go build hello_world.go
This will create an executable file in the same directory.
You can now run your program by typing ./hello_world
into the terminal:
./hello_world
Let's break down the Hello, World!
program.
// Every Go program starts with a package declaration.
// Programs start running in package main.
package main
// import allows us to use code from other packages.
// The fmt package provides functions for formatted I/O.
import "fmt"
// main is the entry point of our program.
func main() {
// Println function of fmt package prints the text to the console.
fmt.Println("Hello, World!")
}
When you run this program, you will see the text Hello, World!
printed to the console.
Today, you learned how to write, compile, and run a simple Go program. You learned about packages, functions, and how to print text to the console.
Next, you might want to learn more about Go's data types, control structures, or how to write functions. The official Go documentation is a great resource.
package main
import "fmt"
func main() {
fmt.Println("Your Name")
}
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now())
}
package main
import "fmt"
func main() {
fmt.Println("5 + 3 =", 5+3)
}
Try to modify these programs and see what happens. The best way to learn programming is by writing code!