Section 4 of 12
Structs & Interfaces
Object-oriented programming in Go with structs and interfaces
Course Progress
Section 4 of 1233% complete
Tutorials
Structs
Structs are collections of fields, Go's way of grouping data together.
Code Examples
Struct Definitiongo
package main
import "fmt"
// Define a struct
type Person struct {
Name string
Age int
Email string
}
// Method on struct
func (p Person) Greet() {
fmt.Printf("Hello, I'm %s\n", p.Name)
}
// Pointer receiver - can modify the struct
func (p *Person) HaveBirthday() {
p.Age++
}
func main() {
// Create struct instance
person := Person{
Name: "Alice",
Age: 25,
Email: "alice@example.com",
}
fmt.Println(person)
person.Greet()
person.HaveBirthday()
fmt.Println(person.Age)
}Interfaces
Interfaces define a set of methods that a type must implement. This enables polymorphism in Go.
Code Examples
Interface Implementationgo
package main
import "fmt"
// Define an interface
type Writer interface {
Write(data string) error
}
type FileWriter struct {
filename string
}
func (fw FileWriter) Write(data string) error {
fmt.Printf("Writing to file %s: %s\n", fw.filename, data)
return nil
}
type ConsoleWriter struct{}
func (cw ConsoleWriter) Write(data string) error {
fmt.Println("Console:", data)
return nil
}
func SaveData(w Writer, data string) {
w.Write(data)
}
func main() {
fw := FileWriter{filename: "output.txt"}
cw := ConsoleWriter{}
SaveData(fw, "Hello")
SaveData(cw, "World")
}Exercises
Shape Calculator
Create structs for Rectangle and Circle with an Area method
INTERMEDIATEStarter Code:
package main
import (
"fmt"
"math"
)
type Rectangle struct {
Width float64
Height float64
}
type Circle struct {
Radius float64
}
// TODO: Implement Area method for Rectangle
// TODO: Implement Area method for Circle
func main() {
rect := Rectangle{Width: 5, Height: 4}
circle := Circle{Radius: 3}
fmt.Println("Rectangle area:", rect.Area())
fmt.Println("Circle area:", circle.Area())
}Hands-on Project
Employee Management System
Create an employee management system with different employee types
ADVANCED
Learning Objectives
- >Design structs
- >Implement interfaces
- >Use polymorphism
Project Tips
- > Start by understanding the requirements
- > Break the project into smaller tasks
- > Test your code frequently as you build
- > Add error handling throughout your code
- > Consider edge cases and validate inputs
- > Document your code with comments