1. BASICS:
package main
import "fmt"
func main() {
// This is single-line comment
/*
Multi-line comment: Declaring string variable
*/
var greeting string = "Hello, Mie!"
fmt.Println(greeting)
}
-
package main
→ entry point of the program -
import
→ bring in packages (likefmt
for printing) -
func main()
→ starting point where execution begins
2. VARIABLES & CONSTANTS:
// Explicit type
var x int = 42
var name string = "Alice"
// Type inference
var y = 10
var greeting = "Hello"
// Shorthand (inside functions only)
z := 5
msg := "Hi"
// Multiple variables
var a, b, c int = 1, 2, 3
d, e := 4, 5
// Constants
const Pi = 3.14159
const Greeting string = "Hello World"
// Multiple constants
const (
StatusOK = 200
StatusNotFound = 404
)
3. DATA TYPES (Basic):
// Boolean
var b bool = true
// String
var s string = "Hello"
// Integers
var i int = 42
var i8 int8 = -128
var i16 int16 = -32768
var i32 int32 = -2147483648
var i64 int64 = -9223372036854775808
// Unsigned Integers
var u uint = 42
var u8 uint8 = 255 // alias: byte
var u16 uint16 = 65535
var u32 uint32 = 4294967295
var u64 uint64 = 18446744073709551615
var up uintptr // pointer integer type
// Floating Point
var f32 float32 = 3.14
var f64 float64 = 3.14159265359
// Complex Numbers
var c64 complex64 = complex(1, 2) // float32 real+imag
var c128 complex128 = complex(5, -7) // float64 real+imag
// Rune (alias for int32, Unicode code point)
var r rune = '世'
// Byte (alias for uint8)
var by byte = 'A'
4. OPERATORS:
// --- Arithmetic Operators ---
a, b := 10, 3
fmt.Println(a + b) // 13 (addition)
fmt.Println(a - b) // 7 (subtraction)
fmt.Println(a * b) // 30 (multiplication)
fmt.Println(a / b) // 3 (integer division)
fmt.Println(a % b) // 1 (modulus)
// --- Relational (Comparison) Operators ---
fmt.Println(a == b) // false
fmt.Println(a != b) // true
fmt.Println(a > b) // true
fmt.Println(a < b) // false
fmt.Println(a >= b) // true
fmt.Println(a <= b) // false
// --- Logical Operators ---
x, y := true, false
fmt.Println(x && y) // false (AND)
fmt.Println(x || y) // true (OR)
fmt.Println(!x) // false (NOT)
// --- Bitwise Operators ---
m, n := 6, 3 // 6 = 110, 3 = 011 in binary
fmt.Println(m & n) // 2 (AND: 110 & 011 = 010)
fmt.Println(m | n) // 7 (OR: 110 | 011 = 111)
fmt.Println(m ^ n) // 5 (XOR: 110 ^ 011 = 101)
fmt.Println(m << 1) // 12 (Left shift: 110 << 1 = 1100)
fmt.Println(m >> 1) // 3 (Right shift: 110 >> 1 = 011)
// --- Assignment Operators ---
c := 5
c += 3 // c = c + 3 → 8
c -= 2 // c = c - 2 → 6
c *= 4 // c = c * 4 → 24
c /= 6 // c = c / 6 → 4
c %= 3 // c = c % 3 → 1
// --- Other Operators ---
// Address-of & Pointer Dereference
val := 42
ptr := &val // address-of
fmt.Println(*ptr) // dereference → 42
5. POINTERS:
// Variable declaration
x := 42
p := &x // pointer to x
*p = 100 // change x through pointer
// Function parameter (pass by reference)
func setTo200(n *int) {
*n = 200
}
setTo200(&x) // x becomes 200
// Function return (return pointer)
func createPointer() *int {
v := 300
return &v
}
ptr := createPointer()
fmt.Println(*ptr) // 300
6. CONTROL STRUCTURES:
// --- If / Else ---
x := 10
if x > 5 {
fmt.Println("x > 5")
} else if x == 5 {
fmt.Println("x == 5")
} else {
fmt.Println("x < 5")
}
// --- Switch ---
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2, 3:
fmt.Println("Tue or Wed")
default:
fmt.Println("Other day")
}
// Expression-less switch
num := 15
switch {
case num%2 == 0:
fmt.Println("Even")
default:
fmt.Println("Odd")
}
// --- For Loops ---
// Classic
for i := 0; i < 3; i++ {
fmt.Println(i)
}
// While-style
j := 0
for j < 3 {
fmt.Println(j)
j++
}
// Infinite loop
// for { fmt.Println("loop") }
// --- Range ---
// Slice
nums := []int{10, 20, 30}
for idx, val := range nums {
fmt.Println(idx, val)
}
// Map
m := map[string]int{"a": 1, "b": 2}
for k, v := range m {
fmt.Println(k, v)
}
// String (runes)
for i, r := range "Go" {
fmt.Printf("%d:%c\n", i, r)
}
// --- Break / Continue ---
for i := 0; i < 5; i++ {
if i == 2 { continue }
if i == 4 { break }
fmt.Println(i)
}
7. COLLECTIONS:
// --- Array ---
// Fixed size, elements of the same type
var arr [3]int = [3]int{1, 2, 3}
fmt.Println(arr[0]) // 1
// --- Slice ---
// Dynamic size, built on arrays (commonly used)
var sl []string = []string{"Go", "Rust", "Python"}
sl = append(sl, "JavaScript")
fmt.Println(sl[0]) // "Go"
// --- Map ---
// Key-value pairs (unordered)
var m map[string]int = map[string]int{"Alice": 25, "Bob": 30}
fmt.Println(m["Alice"]) // 25
8. FUNCTIONS:
// Basic function
func add(a int, b int) int {
return a + b
}
sum := add(3, 5) // 8
// Multiple return values
func divide(a, b int) (int, int) {
q := a / b
r := a % b
return q, r
}
q, r := divide(10, 3) // q=3, r=1
// Named return values
func rectStats(w, h int) (area int, perimeter int) {
area = w * h
perimeter = 2 * (w + h)
return
}
a, p := rectStats(4, 5) // area=20, perimeter=18
// Variadic function
func sumAll(nums ...int) int {
total := 0
for _, v := range nums {
total += v
}
return total
}
total := sumAll(1, 2, 3, 4) // 10
// Function as value
f := add
result := f(10, 20) // 30
// Anonymous function
greet := func(name string) string {
return "Hello " + name
}
msg := greet("Go") // Hello Go
9. STRUCTS & METHODS:
// Struct definition
type Person struct {
Name string
Age int
}
// Create struct instance
p1 := Person{"Alice", 30}
p2 := Person{Name: "Bob"} // Age = 0 by default
// Access fields
fmt.Println(p1.Name) // Alice
fmt.Println(p1.Age) // 30
// Pointer to struct
p3 := &Person{"Charlie", 25}
fmt.Println(p3.Name) // Charlie
// Method with value receiver
func (p Person) Greet() string {
return "Hello, " + p.Name
}
msg := p1.Greet() // Hello, Alice
// Method with pointer receiver (can modify struct)
func (p *Person) HaveBirthday() {
p.Age++
}
p1.HaveBirthday()
fmt.Println(p1.Age) // 31
// Embedding (like inheritance)
type Employee struct {
Person
Position string
}
e := Employee{Person{"Diana", 28}, "Engineer"}
fmt.Println(e.Name) // Diana (from embedded Person)
fmt.Println(e.Position) // Engineer
10. INTERFACES:
// Interface definition
type Shape interface {
Area() float64
Perimeter() float64
}
// Struct implementing interface
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
// Another struct implementing interface
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * 3.14 * c.Radius
}
// Using the interface
var s Shape
s = Rectangle{Width: 4, Height: 5}
fmt.Println(s.Area()) // 20
fmt.Println(s.Perimeter()) // 18
s = Circle{Radius: 3}
fmt.Println(s.Area()) // 28.26
fmt.Println(s.Perimeter()) // 18.84
// Empty interface (can hold any type)
var any interface{}
any = "Hello"
any = 42
any = 3.14
// Type assertion
val, ok := any.(int)
if ok {
fmt.Println("Integer:", val)
}
// Type switch
switch v := any.(type) {
case string:
fmt.Println("string:", v)
case int:
fmt.Println("int:", v)
default:
fmt.Println("unknown type")
}
11. PACKAGES AND MODULES:
// Create a new module (in project folder)
// go mod init mymodule
// Add a dependency
// go get github.com/google/uuid
// go.mod file will track module path and dependencies
// Package example
package mathutil
// Exported function (capitalized)
func Add(a, b int) int {
return a + b
}
// Using a package
import (
"fmt"
"mymodule/mathutil"
)
sum := mathutil.Add(3, 5)
fmt.Println(sum) // 8
// Alias import
import m "mymodule/mathutil"
result := m.Add(2, 4)
// Blank import (import only for side effects)
// import _ "example.com/some/package"
// List all modules and versions
// go list -m all
// Tidy up dependencies
// go mod tidy
12. ERRORS AND PANIC/RECOVER:
import (
"errors"
"fmt"
)
// Built-in error type
err := errors.New("something went wrong")
if err != nil {
fmt.Println(err)
}
// Functions returning error
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
// fmt.Errorf for formatted errors
name := ""
if name == "" {
err := fmt.Errorf("invalid name: %v", name)
fmt.Println(err)
}
// Panic: stops program immediately
// Used for unrecoverable errors
// panic("fatal error")
// Recover: used inside defer to catch panic
func safeDivide(a, b int) (result int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from:", r)
}
}()
if b == 0 {
panic("divide by zero")
}
return a / b
}
fmt.Println(safeDivide(10, 2)) // 5
fmt.Println(safeDivide(10, 0)) // recovered
13. CONCURRENCY (GOROUTINES, CHANNELS AND SELECT):
// Goroutine (lightweight thread)
go fmt.Println("Hello from goroutine")
// Unbuffered channel (synchronizes send/receive)
ch := make(chan int)
// Send to channel
go func() {
ch <- 42
}()
// Receive from channel
val := <-ch
fmt.Println(val) // 42
// Buffered channel
buf := make(chan string, 2)
buf <- "A"
buf <- "B"
fmt.Println(<-buf) // A
fmt.Println(<-buf) // B
// Closing channel
close(ch)
// after close, receive gives zero value
// val, ok := <-ch (ok=false if closed)
// Select with channels
c1 := make(chan string)
c2 := make(chan string)
go func() { c1 <- "one" }()
go func() { c2 <- "two" }()
select {
case msg1 := <-c1:
fmt.Println("Received:", msg1)
case msg2 := <-c2:
fmt.Println("Received:", msg2)
default:
fmt.Println("No message")
}
Top comments (0)