Go is a statically typed, compiled programming language created at Google.It’s designed for simplicity, speed, concurrency, and scalability.You write your own code directly in Go.
Statically Typed Programming Language
- What does "statically typed" mean?
In a statically typed language, the type of every variable is known at compile time (before the program runs). This means the compiler checks and enforces types strictly before your code is executed. - Why is it important?
It helps catch type-related errors early during development, leading to safer and more predictable code. - How does this compare to dynamically typed languages?
In dynamically typed languages (like Python or JavaScript), the types are determined at runtime, which can sometimes lead to unexpected errors if types are used inconsistently. - Example in Go (statically typed):
package main import "fmt" func main() { var age int = 30 // 'age' must always be an integer var name string = "Amrit" // 'name' must always be a string fmt.Println(name, "is", age, "years old.") // The following will cause a compile-time error: // age = "thirty" // Error: cannot assign string to an int variable }
- Here, if you try to assign a value of the wrong type to a variable, the Go compiler will immediately report an error before running the program.
Compiled Programming Language
- What does "compiled" mean?
A compiled language means the source code you write is translated by a compiler into machine code (binary instructions that your computer’s CPU understands) before the program runs. - What happens during compilation?
The compiler performs tasks like checking for errors, optimizing your code, and then producing an executable file. - Benefits of compiled languages:
- Faster execution speed compared to interpreted languages (like Python or JavaScript).
- Early error detection during compilation.
- You get a standalone executable binary that can be run without needing the source code or an interpreter.
- Example:
When you write a Go program (main.go
) and run the command: go build main.go
- This creates an executable file (e.g.,
main.exe
on Windows or justmain
on Linux/Mac) which you can run directly.
What’s different from interpreted languages?
Interpreted languages translate code at runtime, line by line, which can be slower and may detect some errors only when the problematic line is executed.
Go (also called Golang) is a programming language created by Google in 2009.
It is designed to be:
- Simple and easy to learn
- Fast like C or C++
- Efficient with built-in support for concurrency (running many things at once)
- Safe and modern, with automatic memory management
- Great for building web servers, cloud services, command-line tools, and more.
Why learn Go?
- It’s used by big companies like Google, Uber, Dropbox, and more.
- It compiles to fast native code.
- Has great tools to build scalable and maintainable applications.
- Supports goroutines (lightweight threads) for concurrency, making it perfect for networked and distributed system.
How to Run GO Program
Step 1 — Make sure you have Go installed
Check if Go is installed by running this command in your terminal (Command Prompt, PowerShell, or terminal on Mac/Linux):
go version
If it prints something like:
go version go1.22.0 windows/amd64
If Go is not installed, you can download and install it from:
Step 2 — Save your code in a .go
file
- Open any text editor (like VS Code, Notepad++, Sublime Text, etc.)
- Paste your code.
- Save the file with the
.go
extension, for example:
// main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Step 3 — Open terminal and navigate to the folder where you saved main.go
For Example:
cd path\to\your\folder
On Linux/Mac, use /
instead of \
:
cd /path/to/your/folder
Step 4 — Run the program
There are 2 ways to run:
Option 1 — Directly run the file:
go run main.go
Option 2 — Build and run:
First build:
go build main.go
This will create an executable file (main.exe
on Windows, main
on Linux/Mac).
Then run:
./main
Frameworks are higher-level toolkits or libraries built on top of a language.
In Go, you can use libraries or frameworks (like Gin, Echo, Fiber for web APIs), but Go itself is just the language
Top frameworks used for building REST APIs in Go:
Framework | Popularity | Key Features | Use Case |
---|---|---|---|
Gin | Very widely used | Fast, minimalist, great performance, middleware support, easy learning curve | REST APIs, microservices, startups, production apps |
Fiber | Increasing fast | Inspired by Express.js (Node), extremely fast, simple syntax | Lightweight APIs, microservices, high-performance systems |
Echo | Solid user base | More features out-of-the-box than Gin, built-in middleware, very clean routing | Larger APIs, enterprise-level APIs |
Chi | Lightweight, very idiomatic | Fully compatible with net/http, extremely minimal, fully modular | Building fully native Go-style APIs with full control |
If you're starting:
- Gin is the most common recommendation.
- Lots of documentation, community support, tons of examples.
- Scales well for production REST APIs
Variables & Data Types
Variables
A variable is like a named box where you store some data (value). In Go, you must always specify (explicitly or implicitly) the data type of the variable.
Declaring Variables
There are multiple ways to declare variables in Go.
a) Using var
keyword with explicit type
var name string = "Amrit"
var age int = 30
- Here, we declare the variable first (
var name
) - Specify the data type (
string
) - Assign a value (
"Amrit"
)
b) Using var
keyword with type inference
Go is smart and can infer the type from the value:
var city = "Kathmandu" // Go infers city is of type string
But Go still considers it statically typed — the type is determined at compile time.
c) Short variable declaration (most common)
Inside functions, you can use :=
to declare and assign variables:
country := "Nepal" // Same as: var country string = "Nepal"
- This is very common and very clean inside functions.
- You cannot use
:=
outside functions (at the package level).
d) Declaring multiple variables at once
var a, b, c int = 1, 2, 3
or
name, age := "Amrit", 30
e) Zero values (important concept)
If you declare a variable but don’t assign any value, Go assigns it a zero value:
Type | Zero Value |
---|---|
int | 0 |
float | 0.0 |
bool | false |
string | "" (empty string) |
example:
var message string
fmt.Println(message) // prints empty string ""
Data Types
Now let’s go over the most common data types
a) Basic Type
Type | Example |
---|---|
string | "Hello, world" |
int | 42 |
float64 | 3.14 |
bool | true or false |
Example:
var name string = "Amrit"
var age int = 30
var pi float64 = 3.14159
var isGoFun bool = true
b) Integer types (signed)
Type | Size | Range |
---|---|---|
int8 | 8-bit | -128 to 127 |
int16 | 16-bit | -32,768 to 32,767 |
int32 | 32-bit | -2 billion approx |
int64 | 64-bit | very large |
int | platform dependent (usually 32 or 64-bit) |
Example:
var smallNumber int8 = 127
var largeNumber int64 = 10000000000
c) Unsigned integers
Type | Size | Range |
---|---|---|
uint8 | 8-bit | 0 to 255 |
uint16 | 16-bit | 0 to 65535 |
uint32 | 32-bit | 0 to 4 billion |
uint64 | 64-bit | very large |
Example:
var positiveNumber uint32 = 4000000
d) Floating point numbers
Type | Description |
---|---|
float32 | 32-bit floating point |
float64 | 64-bit floating point (more common) |
var temperature float64 = 36.6
e)Boolean
var isActive bool = true
f) Constants
You can also declare constants using const
:
const pi = 3.14159
Constants cannot be changed after assignment.
Module System
“Go uses modules. Each project has its own module.”
In simple words:
- A module is like a container for your Go code.
- It keeps track of your project's dependencies (other packages or modules your project needs).
- Each Go project has its own module (usually represented by a
go.mod
file). - Modules were introduced in Go 1.11 (before that, GOPATH was used).
Why modules?
- To manage dependencies easily.
- To version control your own module.
- To isolate your project from other projects.
- To reproduce builds reliably across machines.
Let’s go step-by-step with an example
1. You want to create a project called myblog
(let’s say you are building a blog API with Go).
mkdir myblog
cd myblog
2. Now you want to initialize your Go module inside this project:
go mod init github.com/amritpanta/myblog
This command creates a file called go.mod
.
You can give any module path (often people give their GitHub repo path if they plan to publish the module). You can also just use myblog
for local testing:
go mod init myblog
3. Your go.mod
file will look like this:
module github.com/amritpanta/myblog
go 1.22
This file tells Go:
- What your module name is
- Which version of Go you’re using
4.Now inside this folder, you can write your Go code.
create main.go
package main
import "fmt"
func main() {
fmt.Println("Welcome to My Blog API")
}
5. Running the code:
go run main.go
6. Now suppose you want to use some external package, for example:
You want to use Gin framework for building your blog API.
go get github.com/gin-gonic/gin
What happens now:
- Go will download the
gin
package - Update your
go.mod
with the new dependency - Create a
go.sum
file (contains checksum for verifying versions)
Your updated go.mod
now looks like:
module github.com/amritpanta/myblog
go 1.22
require github.com/gin-gonic/gin v1.9.0
Concept | Meaning |
---|---|
go.mod | Declares your module name and tracks dependencies |
go.sum | Ensures integrity (security) of dependencies |
Module name | Uniquely identifies your project/module |
go get | Adds external packages as dependencies |
Why "Each project has its own module"?
- Every new project has its own independent
go.mod
- No need to worry about global installations (like
pip
in Python) - Multiple projects can use different versions of the same dependency without conflict
Visual diagram:
myblog/ (your project)
go.mod <-- defines your module
go.sum <-- keeps hash of dependencies
main.go <-- your code
routes/
blog.go
controllers/
post_controller.go
This is the power of modules — clean, isolated, reproducible.
Control Flow in Go
Control flow means how your program makes decisions and repeats actions.
Go has very clean, simple control flow constructs:
1. if
statement
- Syntax is very simple — no parentheses
()
are required. - Curly braces
{}
are mandatory even for single-line blocks.
Basic syntax:
if condition {
// do something
}
2. if...else
statement
if condition {
// true block
} else {
// false block
}
3.if...else if...else
statement
age := 20
if age >= 18 {
fmt.Println("Adult")
} else if age >= 13 {
fmt.Println("Teenager")
} else {
fmt.Println("Child")
}
Inline variable declaration inside if
In Go, you can declare variables inside if
:
if num := 10; num > 5 {
fmt.Println("Number is greater than 5")
}
num
exists only inside the if
block.
2. for
loop
Go has only one loop keyword: for
. It can be used like for
, while
, and infinite
loop.
a) Classic for loop (like C-style):
for i := 0; i < 5; i++ {
fmt.Println(i)
}
- Start with
i := 0
- Loop while
i < 5
- Increment
i++
after each iteration
b) While-style loop
Just omit the init and post statements:
i := 0
for i < 5 {
fmt.Println(i)
i++
}
c) Infinite loop
for {
fmt.Println("Running forever")
}
You must use break
inside to exit, or it will run forever.
d) break
and continue
break
: exit the loop completely.continue
: skip current iteration and move to next.
Example:
for i := 0; i < 5; i++ {
if i == 3 {
continue // skip printing 3
}
fmt.Println(i)
}
3. switch
statement
Switch is very clean in Go — no need for break
, it automatically breaks after each case.
Example:
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Unknown day")
}
Multiple cases together
switch day {
case 1, 2, 3:
fmt.Println("Weekday")
case 6, 7:
fmt.Println("Weekend")
default:
fmt.Println("Unknown day")
}
Switch without expression
You can even write:
num := 10
switch {
case num > 0:
fmt.Println("Positive")
case num < 0:
fmt.Println("Negative")
default:
fmt.Println("Zero")
}
This acts like a cleaner version of multiple if...else
.