# Introduction to Go

Course: [Go](https://www.devtutorials.ai/learn/go) · Section: Go Foundations
Source: https://www.devtutorials.ai/learn/go/foundations/introduction-to-go

> What Go is, why Google made it, its history, features and philosophy, where it is used, how to set it up with Go modules, and how to write your first program with comments.

## What Is Go?

**Go** = a programming language made by Google.

**Programming language** = a set of words and rules you use to give instructions to a computer.

People also call it **Golang**, because its old website was `golang.org`.

With Go, you can build:

- servers that send data to apps
- tools that run in a terminal
- programs that run in the cloud
- programs that do many jobs at the same time

**Simple lesson:** Go is a simple, fast language for building servers, tools and cloud programs.

### A Real-World Example

Your school has a results app.

- Students open the app on their phones.
- The app asks a **server** for their marks.
- The server finds the marks and sends them back.
- On results day, 5,000 students ask at the same time.

A server written in Go can answer all of them quickly.
It can serve many students at once, without waiting for each one to finish.

Boxes with a **Run** button run your Go code right here in your browser.

- **Left side:** the code. You can edit it.
- **Right side:** the **Input** box and the **Output**.
- The first run may take a few seconds while the Go runner loads.
- The runner supports the Go taught in this course. For everything else, install Go on your computer.

## What You Will Learn

In this lesson, you will learn:

1. What Go is, why Google made it, and how it grew.
2. The main features of Go, and the ideas behind it.
3. Where Go is used in the real world.
4. How to install Go and create a Go project.
5. How a Go program is built, and how to write comments.

## Why Go Was Created

Google builds very big programs.
Around 2007, its engineers had three big problems.

Press **Play** to see them.

Compare the three red boxes:

- **Slow builds:** turning code into a program took many minutes.
- **Hard to read:** big languages had too many ways to do one thing.
- **Many CPU cores:** using all the cores of a computer was hard.

So three engineers at Google designed a new language: **Go**.

- **Robert Griesemer**
- **Rob Pike**
- **Ken Thompson**, who also helped create Unix.

Their goals were simple:

- **Build fast**, in seconds.
- **Read easily**, even code someone else wrote.
- **Do many jobs at once**, using every core.

**Simple lesson:** Google made Go to build big programs quickly, keep code easy to read, and use modern computers fully.

## History of Go

Go did not appear in one day.
It grew step by step.

Click each year on the timeline.

### The Key Years

| Year | What happened |
|---|---|
| 2007 | Design of Go starts at Google. |
| 2009 | Go is released as **open source**: free for anyone to use and change. |
| 2012 | **Go 1.0**: the first stable version. |
| 2015 | Go 1.5: Go's own compiler is now written in Go. |
| 2018 | Go 1.11 adds **modules**, a better way to manage projects. |
| 2022 | Go 1.18 adds **generics**, one function for many types. |

### The Go 1 Promise

**Go 1 promise** = code written for Go 1.0 still works on newer Go 1 versions.

- New versions add features.
- They try hard not to break old code.
- So a program you write today should keep working for years.

New Go versions come out twice a year, around February and August.

Your Go version number may be newer than the ones shown in this course. That is fine.

**Simple lesson:** Go started in 2007, became stable in 2012, and keeps old code working as it grows.

## Features of Go

Click each feature to see a small picture of it.

### 1. Simple

- Go has only **25 keywords**.
- **Keyword** = a word with a special meaning in the language, like `func` or `if`.
- There is usually one clear way to write something.
- So code written by different people looks alike.

### 2. Fast to Build and Fast to Run

**Compiler** = a tool that checks your code and turns it into a program the computer can run.

- Go's compiler is very quick, even for big projects.
- The finished program runs fast, because it is already in machine code.

### 3. One Program File

- `go build` makes **one file** that holds the whole program.
- You copy that file to another computer and run it.
- That computer does not need Go installed.

### 4. Built for Many Jobs at Once

**Concurrency** = a program working on many jobs at the same time.

- Go has **goroutines**: very light workers that run jobs at the same time.
- You will learn them in **Goroutines**.

### 5. Safe

- **Static typing** = Go checks the type of every value before the program runs.
- **Garbage collection** = Go frees memory you no longer use, automatically.
- Both stop many common bugs.

### 6. Tools Included

- `go fmt` formats your code neatly.
- `go test` runs your tests.
- `go vet` warns about code that looks wrong.

**Simple lesson:** Go is simple, fast, safe, makes one program file, and does many jobs at once.

## The Go Philosophy

**Philosophy** = the ideas that guide how something is made.

Go's makers chose a few clear ideas:

- **Simple is better than clever.** Code should be easy to read, not show off.
- **Less is more.** Go left out many features on purpose.
- **Clear over short.** A few more lines are fine if they are easier to understand.
- **Errors are values.** Go makes you check for problems right where they happen.
- **Composition over inheritance.** Build big things from small parts. You will see this in **Composition and Embedding**.

### A Small Story

Think of two school notice boards.

- **Board A** has notices in ten different styles, colours and sizes.
- **Board B** has every notice in the same simple format.
- On Board B, you find any notice in seconds.

Now the mapping:

- **Go is Board B.** Every Go program follows the same simple style, so it is quick to read.

**Simple lesson:** Go chooses simple and clear code over clever and short code.

## Applications of Go

Go is used in six main kinds of work.
Click each tab.

Click each tab and compare:

- **The left box:** the kind of program.
- **The right box:** a real example of it.

### Backend Development

**Backend** = the part of a system that runs on a server, not on your screen.

- Go handles many requests at once.
- Example: an API that sends exam results to an app.

### Cloud-Native Applications

**Cloud-native** = built to run on cloud servers that grow and shrink on demand.

- **Docker** and **Kubernetes**, two of the most used cloud tools, are written in Go.

### Microservices

**Microservice** = a small program that does one job, and talks to other small programs.

- Example: one service for fees, one for results, one for login.
- Go's small, fast program files suit this well.

### DevOps Tools

**DevOps** = the work of building, testing and running software every day.

- Tools like **Terraform** and **Prometheus** are written in Go.

### Networking Applications

- Go has strong built-in packages for networks.
- Example: a chat server, or a web server like **Caddy**.

### Command-Line Applications

**Command-line app** = a program you run by typing in a terminal.

- Example: **Hugo** builds websites, and **gh** is GitHub's terminal tool.
- One small program file makes these easy to share.

**Simple lesson:** Go is used most for servers, cloud tools and command-line programs.

## Go Environment Setup

To run Go on your computer, you install the **Go toolchain**.

**Toolchain** = the compiler and the `go` command, which builds, runs and tests your code.

### Installing Go

1. Open `go.dev/dl` in your browser.
2. Download the installer for your system.
3. Run it and follow the steps.

Pick your system:

- **Windows:** run the `.msi` file.
- **macOS:** run the `.pkg` file, or type `brew install go`.
- **Linux:** follow the steps on `go.dev/doc/install`.

### Checking Go Version

Open a new **terminal** and type:

```bash
go version
```

**Terminal** = a window where you type commands, like Command Prompt or PowerShell on Windows.

You see something like:

```text
go version go1.24.0 windows/amd64
```

- `go1.24.0` is the Go version.
- `windows/amd64` is your system and processor type.

### Watch the Whole Setup

Click **Next step** to walk through each command.
Watch the folder on the right fill up.

Look at two things:

- **The terminal** shows each command and what it prints.
- **The folder** shows the files each command creates.

### Setting Up a Workspace

**Workspace** = the folder where you keep your Go projects.

- Make one folder for all your practice, like `D:\GoPractice`.
- Inside it, make one folder per project, like `hello`.
- Keep each project in its own folder, with its own `go.mod`.

### Understanding GOPATH

**GOPATH** = a folder Go uses for its own files.

- By default, it is the `go` folder in your home folder.
- On Windows, that is like `C:\Users\Asha\go`.
- Downloaded packages are stored inside it.
- Tools you install go in its `bin` folder.
- You can see it with `go env GOPATH`.

Switch between the two tabs and compare:

- **Today:** your project can be in any folder.
- **Before 2018:** every project had to sit inside GOPATH.

### Using Go Modules

**Module** = a Go project, marked by a file named `go.mod`.

**`go.mod`** = a small text file that holds the project's name and the Go version.

A new `go.mod` looks like this:

```text
module example.com/hello

go 1.24
```

- `module example.com/hello` is the project's name, called the **module path**.
- `go 1.24` is the Go version the project needs.
- You will learn more in **Packages and Modules**.

### Creating a Go Project

```bash
mkdir hello
cd hello
go mod init example.com/hello
```

- `mkdir hello` makes a new folder.
- `cd hello` moves you inside it.
- `go mod init` creates `go.mod`.

### Running a Go Program

There are two ways:

- `go run .` builds and runs the program in this folder, in one step.
- `go build` makes a program file you can keep, then you run that file.

### Common Setup Problems

| Problem | Why it happens | How to fix it |
|---|---|---|
| `'go' is not recognized` or `command not found` | The terminal cannot find Go. | Close the terminal and open a new one. If it still fails, add Go's `bin` folder to **PATH**. |
| `go: cannot find main module` | There is no `go.mod` here. | Run `go mod init example.com/hello` first. |
| `package hello is not in std` | You ran `go run hello` instead of a file or folder. | Use `go run .` or `go run main.go`. |
| Old version shows | An older Go is installed too. | Remove the old one and install again. |

**PATH** = a list of folders where your computer looks for commands.

**Simple lesson:** install Go, check `go version`, make a folder, run `go mod init`, then `go run .`.

## Your First Go Program

Here is the smallest useful Go program.
Press **Run**.

```go runnable title="Your first Go program"
package main

import "fmt"

func main() {
	fmt.Println("Hello, Go!")
}
```

```text
Hello, Go!
```

- `fmt.Println()` shows text in the output, then moves to a new line.
- The text goes inside **double quotes**: `"Hello, Go!"`.

### Program Structure

Click each part to see what it does.

### package main

**Package** = a group of Go files that belong together.

- Every Go file starts with a `package` line.
- `package main` means: this file makes a **program you can run**.
- Other package names make **libraries**: code for other programs to use.

### import

**import** = bring in ready-made code from another package.

- `import "fmt"` brings in the **fmt** package.
- **fmt** (say "fumt" or "format") has functions to print and read text.
- To import two packages, use brackets:

```go
import (
	"fmt"
	"strings"
)
```

### The main() Function

**Function** = a named group of instructions.

**`func main()`** = the function where every Go program starts.

- `func` is the keyword that makes a function.
- Go runs `main()` when the program starts.
- When `main()` ends, the program ends.

### Statements

**Statement** = one instruction for the computer.

- `fmt.Println("Hello, Go!")` is one statement.
- Go puts one statement on each line.
- You do **not** type a semicolon `;` at the end. Go adds it for you.

**Code block** = statements inside curly braces `{ }`.

- `{` must be on the **same line** as `func main()`.
- Every `{` needs its own `}`.

**Simple lesson:** a Go program has a package line, imports, and `main()`, whose statements run in order.

## How Go Runs Your Program

### From Code to Program

Go is a **compiled** language.
Press **Play** to see what that means.

- **Compiled** = the whole program is checked and translated first, then it runs.
- If a rule is broken, nothing runs. You get an error with a line number.

### Statements Run from Top to Bottom

Press **Play** and watch the output grow, one line at a time.

Now try it yourself.
Change the order of the lines, then press **Run**.

```go runnable title="Statements run from top to bottom"
package main

import "fmt"

func main() {
	fmt.Println("Good morning, class!")
	fmt.Println("Today is Maths day.")
	fmt.Println("Bring your geometry box.")
}
```

```text
Good morning, class!
Today is Maths day.
Bring your geometry box.
```

### Print and Println

- `fmt.Println` adds a new line at the end.
- `fmt.Print` does **not** add a new line.
- `fmt.Println` puts a space between two values. `fmt.Print` adds a space only between two values that are not text.

```go runnable title="Print vs Println"
package main

import "fmt"

func main() {
	fmt.Print("Roll no: ")
	fmt.Println(12)
	fmt.Println("Name:", "Arjun", "Class:", 8)
}
```

```text
Roll no: 12
Name: Arjun Class: 8
```

### Go Is Strict: Unused Imports

Go does not allow an import you do not use.
Run this code.

```go runnable expect-error title="An unused import"
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println("Hello!")
}
```

```text
./prog.go:5:2: "strings" imported and not used
```

- `5:2` means **line 5, column 2**.
- Fix: remove the `"strings"` line, or use it.
- Go is strict on purpose: unused code makes programs slower to build and harder to read.

### The Brace Must Stay on the Same Line

Run this code. The `{` is on the next line.

```go runnable expect-error title="A brace on the wrong line"
package main

import "fmt"

func main()
{
	fmt.Println("Hello!")
}
```

Go stops with an error like `syntax error: unexpected semicolon or newline before {`.

- Go adds a hidden `;` at the end of the line `func main()`.
- Then `{` is left alone on the next line, which is not allowed.
- Fix: write `func main() {` on one line.

### Typing Input into Your Program

A program can also **read** what you type.

- `var name string` makes a box called `name` that holds text.
- `fmt.Scan(&name)` reads one word from the input into that box.
- You will learn `var` in **Variables and Constants**, and `&` in **Pointers**.

Type a name in the **Input** box, then press **Run**.

```go runnable stdin="Meena" title="A program that reads your name"
package main

import "fmt"

func main() {
	var name string
	fmt.Println("What is your name?")
	fmt.Scan(&name)
	fmt.Println("Welcome to Green Valley School,", name)
}
```

```text
What is your name?
Welcome to Green Valley School, Meena
```

In this lab, programs run in your browser with a Go interpreter compiled to WebAssembly.

- It runs the Go taught in this course.
- Some error messages may be worded a little differently from the real `go` tool.
- For full Go, install it on your computer, or use the Go Playground at `go.dev/play`.

**Simple lesson:** Go checks the whole program first, then runs `main()` from top to bottom.

## Comments

**Comment** = a note in your code for people. Go skips it.

Comments help you:

- explain **why** the code does something
- remember things when you open the code later
- switch a line off for a moment, without deleting it

Go has two kinds of comments.

### Single-Line Comments

Start with `//`.
Go skips everything after it, up to the end of the line.

```go runnable title="Single-line comments"
package main

import "fmt"

func main() {
	// Print the student's name
	fmt.Println("Name: Priya")
	fmt.Println("Class: 7A") // a comment can also go after code
}
```

```text
Name: Priya
Class: 7A
```

### Multi-Line Comments

Start with `/*` and end with `*/`.
Everything between them is skipped, across many lines.

```go runnable title="A multi-line comment"
package main

import "fmt"

func main() {
	/* This program prints a report card.
	   Marks are out of 100.
	   Update them at the end of each term. */
	fmt.Println("Maths: 92")
}
```

```text
Maths: 92
```

### Doc Comments

**Doc comment** = a `//` comment written just above a function or package.

- It starts with the name of the thing it describes.
- Editors show it when you point at the name.
- The `go doc` tool shows it as help.

```go runnable title="A doc comment"
package main

import "fmt"

// welcome prints a greeting for new students.
func welcome() {
	fmt.Println("Welcome to Green Valley School!")
}

func main() {
	welcome()
}
```

```text
Welcome to Green Valley School!
```

### See What Go Skips

Switch to **What Go runs** and compare:

- **Comment lines** are crossed out, because Go skips them.
- **Code lines** stay, and only they print something.

**Easy way to remember**

- `//` = one line
- `/* */` = many lines
- `// Name ...` above a function = help for others

**Simple lesson:** comments are notes for people, and Go never runs them.

## TL;DR

1. **Go** = a simple, fast programming language made by Google.
   - Designed in 2007, open source in 2009, stable (Go 1.0) in 2012.
2. **Features** = simple, fast, one program file, concurrency, safe, tools included.
3. **Philosophy** = simple and clear code over clever code.
4. **Uses** = backend, cloud-native, microservices, DevOps, networking, command-line apps.
5. **Setup** = install from `go.dev/dl`, then:
   - `go version`
   - `go mod init example.com/hello`
   - `go run .`
6. **Program** = `package main` + `import "fmt"` + `func main() { }`.
   - **Statement** = one instruction, one per line, no `;` needed.
7. **Comments** = `//` and `/* */`. Go skips them.

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| No `package main` | The first line can be anything | A program starts with `package main` | The program will not build. |
| `{` on the next line | Braces can go anywhere | `{` stays on the same line as `func main()` | `unexpected semicolon or newline before {` |
| An unused import | Extra imports do no harm | Every import must be used | `"strings" imported and not used` |
| `fmt.println("Hi")` | Capital letters do not matter | Go cares about case: `Println` | `undefined: fmt.println` |
| Single quotes for text | `'Hello'` is text | Text uses double quotes: `"Hello"` | An error about a rune or a bad character. |
| `go run` outside the project | It works from any folder | Run it inside the folder with `go.mod` | `cannot find main module` |
| Projects inside GOPATH only | Old guides say so | With modules, any folder works | Confusing setup, for no reason. |

## Check Yourself

## Exercises

## What to Remember

- Go is a simple, fast language made by Google.
- It is used for servers, cloud tools, microservices and command-line apps.
- Set up a project with `go mod init`, and run it with `go run .`.
- Every program has `package main`, its imports, and `func main()`.
- Go is strict: no unused imports, and `{` stays on the same line.
- Comments are notes for people. Go skips them.

Next: **Variables and Constants**. You will learn how to store values like names and marks, and use them in your program.
