0% found this document useful (0 votes)
22 views

# Go Programming Course

Uploaded by

tung
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

# Go Programming Course

Uploaded by

tung
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

# Go Programming Course

## Week 3: Custom Types and Interfaces


Version 1.0 - January 2025

## Table of Contents

1. Collection Types
- Arrays
- Slices
- Maps

2. Module 05: Structs


- Basic Concepts
- Methods
- Composition
- Tags and Serialization

3. Module 06: Interfaces


- Interface Basics
- Empty Interface
- Type Assertions
- Common Patterns

---

# Collection Types in Go

## Arrays
Arrays in Go provide fixed-size, ordered collections of elements. Understanding arrays is
fundamental to working with more complex data structures.

### Key Concepts


1. Fixed Size
2. Zero-based Indexing
3. Type Consistency
4. Value Semantics

### Basic Array Operations


```go
// Declaration and initialization
var numbers [5]int // Zero-valued array
cities := [4]string{
"New York",
"London",
"Tokyo",
"Paris",
}
// Accessing elements
firstCity := cities[0] // "New York"
cities[1] = "Berlin" // Modifying an element

// Array length
length := len(cities) // 4
```

## Slices
Slices provide dynamic, flexible views into arrays. They are the most commonly used
collection type in Go.

### Key Features


1. Dynamic Size
2. Reference Type
3. Built-in Append Function
4. Capacity Management

### Working with Slices


```go
// Creating slices
numbers := []int{1, 2, 3, 4, 5}
subset := numbers[1:4] // [2, 3, 4]

// Using make
dynamicSlice := make([]int, 3, 5) // Length 3, Capacity 5

// Appending elements
numbers = append(numbers, 6, 7)
```

## Maps
Maps implement key-value pair storage, providing fast lookups and flexible data
organization.

### Essential Operations


```go
// Map creation
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}

// Adding and accessing


ages["Charlie"] = 35
aliceAge := ages["Alice"]

// Checking existence
value, exists := ages["David"]
if !exists {
fmt.Println("David not found")
}
```

---

# Module 05: Structs

## Basic Struct Concepts

### Definition and Creation


Structs group related data into a single unit, forming the basis for custom types in Go.

```go
type Person struct {
Name string
Age int
Address Address
}

type Address struct {


Street string
City string
Country string
}

// Creating instances
person := Person{
Name: "Alice Johnson",
Age: 30,
Address: Address{
Street: "123 Go Lane",
City: "Techville",
Country: "Gopher Land",
},
}
```

### Methods and Receivers


```go
// Value receiver
func (p Person) GetFullName() string {
return p.Name
}

// Pointer receiver
func (p *Person) Birthday() {
p.Age++
}
```

## Struct Composition
Go uses composition over inheritance, allowing for flexible type creation.

```go
type Employee struct {
Person // Embedded struct
Position string
Salary float64
}

func (e Employee) GetSalaryDetails() string {


return fmt.Sprintf("%s earns %.2f", e.Name, e.Salary)
}
```

---

# Module 06: Interfaces

## Interface Basics
Interfaces define behavior through method signatures, enabling polymorphic code design.

### Definition and Implementation


```go
type Writer interface {
Write([]byte) (int, error)
}

type FileWriter struct {


filename string
}

func (fw FileWriter) Write(data []byte) (int, error) {


return len(data), nil
}
```

## Empty Interface and Type Assertions


The empty interface (`interface{}`) can hold values of any type, requiring type assertions for
specific operations.

```go
func processValue(v interface{}) {
switch val := v.(type) {
case int:
fmt.Printf("Integer: %d\n", val)
case string:
fmt.Printf("String: %s\n", val)
default:
fmt.Printf("Unknown type\n")
}
}
```

## Best Practices

### Struct Best Practices


1. Keep structs focused and cohesive
2. Use pointer receivers for methods that modify state
3. Leverage composition for code reuse
4. Document exported fields and methods

### Interface Best Practices


1. Keep interfaces small and focused
2. Design interfaces for behavior, not data
3. Use composition to build larger interfaces
4. Implement interfaces implicitly

## Practice Exercises

### Struct Exercises


1. Create a Library Management System
- Design book and member structs
- Implement checkout system
- Handle due dates and fines

2. Build a Shape Calculator


- Define different shapes using structs
- Implement area and perimeter methods
- Use composition for complex shapes

### Interface Exercises


1. Implement a Logging System
- Define logger interface
- Create multiple logger implementations
- Support different output formats

2. Design a Payment System


- Create payment processor interface
- Implement different payment methods
- Handle transaction validation
## Additional Resources
1. Go Documentation: https://golang.org/doc/
2. Go by Example: https://gobyexample.com/
3. Effective Go: https://golang.org/doc/effective_go
4. Go Playground: https://play.golang.org/

---

© 2025 Go Programming Course. All rights reserved.

You might also like