Structs in Go are a fundamental way to group related data into a single entity. They allow us to create complex types that represent real-world entities, making our code more organized and easier to manage. In this article, we’ll explore three diverse examples of defining and using structs in Go, showcasing their practical applications.
We often need to represent books in applications, encompassing various attributes like title, author, and publication year. This example demonstrates how to define a struct for a book and use it to print book details.
package main
import (
"fmt"
)
type Book struct {
Title string
Author string
Year int
}
func main() {
myBook := Book{
Title: "1984",
Author: "George Orwell",
Year: 1949,
}
fmt.Printf("Title: %s\nAuthor: %s\nYear: %d\n", myBook.Title, myBook.Author, myBook.Year)
}
In a library management system, we might have a struct for a Library that contains multiple Books. This example illustrates how to define nested structs and iterate through a collection of books in a library.
package main
import (
"fmt"
)
type Book struct {
Title string
Author string
Year int
}
type Library struct {
Name string
Books []Book
}
func main() {
library := Library{
Name: "City Library",
Books: []Book{
{Title: "1984", Author: "George Orwell", Year: 1949},
{Title: "Brave New World", Author: "Aldous Huxley", Year: 1932},
},
}
fmt.Printf("Library: %s\nBooks:\n", library.Name)
for _, book := range library.Books {
fmt.Printf("- %s by %s (%d)\n", book.Title, book.Author, book.Year)
}
}
Books
field in the Library
struct is a slice of Book
, allowing for dynamic lists of books.Library
struct that perform operations like adding or removing books.In an educational application, we may want to manage student records. This example demonstrates how to define a struct for a Student, including methods to calculate their average grade.
package main
import (
"fmt"
)
type Student struct {
Name string
Grades []float64
}
func (s Student) AverageGrade() float64 {
total := 0.0
for _, grade := range s.Grades {
total += grade
}
return total / float64(len(s.Grades))
}
func main() {
student := Student{
Name: "Alice",
Grades: []float64{88.5, 92.0, 79.5},
}
fmt.Printf("Student: %s\nAverage Grade: %.2f\n", student.Name, student.AverageGrade())
}
AverageGrade
, showcasing how you can encapsulate behavior related to the struct data.