Go Tutorial menu

Go Introduction

Go is a simple, fast and reliable programming language created at Google.

What is Go?

  • Go was designed at Google in 2007 and released publicly in 2009
  • It is a compiled language: your code is turned into a program file that runs directly
  • It is statically typed: every variable has a fixed type
  • It is known for being simple, with very few keywords

What is Go Used For?

AreaExample
Web servers and APIsBackends for apps and websites
Cloud toolsDocker, Kubernetes, Terraform
Command-line toolsSmall programs you run in the terminal
NetworkingProxies, chat servers, services that handle many users

How to Run Go

  1. Go Playground: open go.dev/play in a browser, paste code, click Run. Nothing to install.
  2. On your computer: download Go from go.dev/dl and install it. Check it with go version in the terminal.

To run a file on your computer, save it as main.go and type:

Example

bash
go run main.go

Your First Program

Example

go
package main

import "fmt"

func main() {
	fmt.Println("Hello, Workownix!")
}
Output
Hello, Workownix!

The example explained

LineWhat it does
package mainEvery Go file belongs to a package. main makes it a runnable program
import "fmt"Loads the fmt package, used for printing (format)
func main()The function where the program starts
fmt.Println(...)Prints the text and a new line

Go is strict: if you import a package or create a variable and never use it, the program will not compile. This keeps code clean.

Printing Output

The fmt package has three main print functions:

Example

go
package main

import "fmt"

func main() {
	fmt.Print("Karachi ")
	fmt.Print("Lahore\n")
	fmt.Println("Price:", 250, "rupees")
	fmt.Printf("%s has %d students\n", "Class A", 30)
}
Output
Karachi Lahore
Price: 250 rupees
Class A has 30 students
  • Print prints exactly what you give it. \n is a new line.
  • Println adds spaces between values and a new line at the end.
  • Printf uses verbs like %s (string) and %d (whole number) to place values.

Comments

Example

go
// A single-line comment

/* A comment
   over several lines */

Go ignores comments. Use them to explain why your code does something.

Formatting Your Code

Go has an official style. The command go fmt formats your file automatically, and most editors run it when you save. Go code uses tabs for indentation, and the opening { must stay on the same line as func or if.

Exercise

Exercise

Which line is needed to make a Go file a runnable program?

Learn Go with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp