Learn Golang
  • Learn Go
  • The Basics
    • Installing Go
    • Hello World
  • Language Features
    • Basic Input Output
    • Variable Basics
    • Control Statements
    • Loops
    • Functions
    • Recursion
  • Data Structures
    • Arrays
    • Slices
    • Maps
    • Pointers
    • Structs
  • Other Concepts
    • Sorting
    • Interfaces
    • Generics
    • Goroutines
  • References
Powered by GitBook
On this page
  1. The Basics

Hello World

Running the "Hello World" program in golang

PreviousInstalling GoNextBasic Input Output

Last updated 2 years ago

CtrlK

Our first program will be the classic "hello world" program. To run this in go, create a new file called hello.go On MacOS create the file by running

$ touch hello.go

Open the file in your favorite text editor (or VSCode which we will be using in this documentation), and paste the following code into it:

hello.go
package main

import "fmt"
func main() {
    fmt.Println("hello world")
}

Save the file, and in your terminal, run the following command to execute the file

$ go run hello.go
# this will output: hello world

Explanation of the code

In the code above, line 1 is the package declaration name. Go links all the packages during runtime for program execution beginning with the main package. The main function is also important here since this is where program execution begins. That is, the main function is the function that is called whenever we run a golang program file.

As per the golang language specs:

The main package must have package name main and declare a function main that takes no arguments and returns no value.

func main() { … }

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits.

The second bit worth pointing out is the import "fmt" line. fmt is short for format, and it is a package that implements I/O formatting, similar to the printf and scanf implemented in the C programming language. It even uses the same formatting verbiage as C. That is, %s for strings, %d for integers, and so on. See a full list of the verbs here: https://pkg.go.dev/fmt

For the next section, we will go over the basic data types in golang.