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?
| Area | Example |
|---|---|
| Web servers and APIs | Backends for apps and websites |
| Cloud tools | Docker, Kubernetes, Terraform |
| Command-line tools | Small programs you run in the terminal |
| Networking | Proxies, chat servers, services that handle many users |
How to Run Go
- Go Playground: open go.dev/play in a browser, paste code, click Run. Nothing to install.
- On your computer: download Go from go.dev/dl and install it. Check it with
go versionin the terminal.
To run a file on your computer, save it as main.go and type:
Example
go run main.goYour First Program
Example
package main
import "fmt"
func main() {
fmt.Println("Hello, Workownix!")
}Hello, Workownix!
The example explained
| Line | What it does |
|---|---|
package main | Every 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
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)
}Karachi Lahore Price: 250 rupees Class A has 30 students
Printprints exactly what you give it.\nis a new line.Printlnadds spaces between values and a new line at the end.Printfuses verbs like%s(string) and%d(whole number) to place values.
Comments
Example
// 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?
