Summary: in this tutorial, you will learn how to develop the Go Hello World program.
Creating a project
First, create a new directory to store the Go source code files.
mkdir hello-worldSecond, navigate to the project directory:
cd hello-worldDefining the Go Hello World Program
Create a new file called main.go within the hello-world directory with the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Code language: Go (go)How it works.
First, define the main package:
package mainCode language: Go (go)Go uses packages to organize code. Each package may contain one or more source code files. In this example, we define a package called main, which is a special package in Go.
When you run a Go program, the Go runtime looks for the main package first. Therefore, every Go application must have the main package.
The Go runtime is responsible for installing your program code and dependencies and executing the program in the target environment.
Second, import the standard library fmt which includes many useful functions for formatting text and displaying text to the console:
import "fmt"Code language: Golo (golo)Third, declare the main function:
func main() {
fmt.Println("Hello, World!")
}Code language: Go (go)In Go, a function is a reusable block of code. To define a function, you use the func keyword. In this example, we define the main function.
The main() is a special function, which serves as the entry point for every Go program. When you run a Go program, the Go runtime executes the main() function in the main package first. Therefore, a Go program must have the main package and main() function.
The parentheses after the main function name () indicate that the main() function does not take any arguments.
The opening and closing curly braces ({}) indicate the beginning and ending of a function.
Inside the main() function, we call the Println() function of the fmt package to display the message "Hello, World!" to the console:
fmt.Println("Hello, World!")Code language: JavaScript (javascript)Running the Go Hello World program
Open your terminal and navigate to the project directory:
cd hello-worldCode language: plaintext (plaintext)Compile, build, and run the Go program:
go run main.goCode language: plaintext (plaintext)It’ll return the following output on the console:
Hello, World!Code language: plaintext (plaintext)Summary
- Go uses packages to organize code.
- Use
importto include other packages. - Use the
funckeyword to define a function. - Every Go program must have a
mainpackage that contains amain()function. Themain()function serves as an entry point for every Go program. - Use the go run command to compile, build, and run a Go program.