Learning Go Concepts
1. Basic Syntax and Structure
Hello World
1package main
2
3import "fmt"
4
5func main() {
6 fmt.Println("Hello, World!")
7}
Every Go program starts with a package declaration. The main
package is special - it’s the entry point of executable programs.
2. Variables and Data Types
Variable Declarations
1// Explicit type declaration
2var name string = "John"
3var age int = 25
4
5// Type inference
6var city = "New York"
7
8// Short variable declaration (only inside functions)
9country := "USA"
Basic Data Types
- Integers:
int
,int8
,int16
,int32
,int64
- Unsigned integers:
uint
,uint8
,uint16
,uint32
,uint64
- Floating point:
float32
,float64
- Boolean:
bool
- String:
string
- Byte:
byte
(alias for uint8) - Rune:
rune
(alias for int32, represents Unicode code points)
3. Control Structures
If Statements
1if age >= 18 {
2 fmt.Println("Adult")
3} else if age >= 13 {
4 fmt.Println("Teenager")
5} else {
6 fmt.Println("Child")
7}
8
9// If with initialization
10if x := 10; x > 5 {
11 fmt.Println("x is greater than 5")
12}
Loops
Go has only one loop construct: for
1// Traditional for loop
2for i := 0; i < 10; i++ {
3 fmt.Println(i)
4}
5
6// While-like loop
7count := 0
8for count < 5 {
9 fmt.Println(count)
10 count++
11}
12
13// Infinite loop
14for {
15 // Loop forever (use break to exit)
16}
17
18// Range loop
19numbers := []int{1, 2, 3, 4, 5}
20for index, value := range numbers {
21 fmt.Printf("Index: %d, Value: %d\n", index, value)
22}
Switch Statements
1switch day := "Monday"; day {
2case "Monday":
3 fmt.Println("Start of work week")
4case "Friday":
5 fmt.Println("TGIF!")
6case "Saturday", "Sunday":
7 fmt.Println("Weekend!")
8default:
9 fmt.Println("Regular day")
10}
4. Functions
Basic Function Syntax
1func add(a int, b int) int {
2 return a + b
3}
4
5// Multiple parameters of same type
6func multiply(a, b int) int {
7 return a * b
8}
9
10// Multiple return values
11func divide(a, b int) (int, error) {
12 if b == 0 {
13 return 0, fmt.Errorf("division by zero")
14 }
15 return a / b, nil
16}
Named Returns
1func rectangle(length, width int) (area, perimeter int) {
2 area = length * width
3 perimeter = 2 * (length + width)
4 return // naked return
5}
Variadic Functions
1func sum(numbers ...int) int {
2 total := 0
3 for _, num := range numbers {
4 total += num
5 }
6 return total
7}
8
9// Usage: sum(1, 2, 3, 4, 5)
5. Data Structures
Arrays
1// Fixed size
2var arr [5]int
3arr[0] = 10
4
5// Initialize with values
6numbers := [5]int{1, 2, 3, 4, 5}
7
8// Let compiler count
9auto := [...]int{1, 2, 3}
Slices
1// Dynamic arrays
2var slice []int
3slice = append(slice, 1, 2, 3)
4
5// Create with make
6slice2 := make([]int, 5) // length 5, capacity 5
7slice3 := make([]int, 5, 10) // length 5, capacity 10
8
9// Slice operations
10numbers := []int{1, 2, 3, 4, 5}
11subset := numbers[1:4] // [2, 3, 4]
Maps
1// Create map
2ages := make(map[string]int)
3ages["Alice"] = 25
4ages["Bob"] = 30
5
6// Map literal
7scores := map[string]int{
8 "Alice": 95,
9 "Bob": 87,
10 "Carol": 92,
11}
12
13// Check if key exists
14if age, exists := ages["Alice"]; exists {
15 fmt.Printf("Alice is %d years old\n", age)
16}
17
18// Delete key
19delete(ages, "Bob")
Structs
1type Person struct {
2 Name string
3 Age int
4 Email string
5}
6
7// Create struct
8p1 := Person{
9 Name: "John",
10 Age: 30,
11 Email: "john@example.com",
12}
13
14// Anonymous struct
15point := struct {
16 X, Y int
17}{10, 20}
6. Pointers
1func main() {
2 x := 42
3 p := &x // p is a pointer to x
4 fmt.Println(*p) // dereference pointer, prints 42
5
6 *p = 21 // change value through pointer
7 fmt.Println(x) // prints 21
8}
9
10// Pointers with structs
11func (p *Person) UpdateAge(newAge int) {
12 p.Age = newAge
13}
7. Methods and Interfaces
Methods
1type Rectangle struct {
2 Width, Height float64
3}
4
5// Method with value receiver
6func (r Rectangle) Area() float64 {
7 return r.Width * r.Height
8}
9
10// Method with pointer receiver
11func (r *Rectangle) Scale(factor float64) {
12 r.Width *= factor
13 r.Height *= factor
14}
Interfaces
1type Shape interface {
2 Area() float64
3 Perimeter() float64
4}
5
6type Circle struct {
7 Radius float64
8}
9
10func (c Circle) Area() float64 {
11 return 3.14159 * c.Radius * c.Radius
12}
13
14func (c Circle) Perimeter() float64 {
15 return 2 * 3.14159 * c.Radius
16}
17
18// Circle automatically implements Shape interface
8. Error Handling
1import (
2 "errors"
3 "fmt"
4)
5
6func divide(a, b float64) (float64, error) {
7 if b == 0 {
8 return 0, errors.New("division by zero")
9 }
10 return a / b, nil
11}
12
13func main() {
14 result, err := divide(10, 0)
15 if err != nil {
16 fmt.Printf("Error: %v\n", err)
17 return
18 }
19 fmt.Printf("Result: %f\n", result)
20}
9. Goroutines and Channels
Goroutines (Concurrent execution)
1import (
2 "fmt"
3 "time"
4)
5
6func sayHello(name string) {
7 for i := 0; i < 3; i++ {
8 fmt.Printf("Hello, %s!\n", name)
9 time.Sleep(100 * time.Millisecond)
10 }
11}
12
13func main() {
14 go sayHello("Alice") // runs concurrently
15 go sayHello("Bob") // runs concurrently
16
17 time.Sleep(1 * time.Second) // wait for goroutines
18}
Channels
1func main() {
2 ch := make(chan string)
3
4 go func() {
5 ch <- "Hello from goroutine!"
6 }()
7
8 message := <-ch // receive from channel
9 fmt.Println(message)
10}
11
12// Buffered channel
13ch := make(chan int, 3)
10. Packages and Imports
Creating a Package
1// In file math/calculator.go
2package math
3
4func Add(a, b int) int {
5 return a + b
6}
7
8func subtract(a, b int) int { // lowercase = private
9 return a - b
10}
Using the Package
1package main
2
3import (
4 "fmt"
5 "yourproject/math"
6)
7
8func main() {
9 result := math.Add(5, 3)
10 fmt.Println(result)
11}
Key Go Principles
- Simplicity: Go favors simple, readable code over clever solutions
- Composition over Inheritance: Use interfaces and embedding instead of traditional inheritance
- Explicit Error Handling: Errors are values, handle them explicitly
- Concurrency: Goroutines and channels make concurrent programming easier
- Fast Compilation: Go compiles quickly to native machine code