Composite Types
Composite types are types that are composed of other types. The main composite types are arrays, slices, maps, structs and etc.
Arrays
Arrays in Go are fixed-size sequences of elements of the same type. The size of an array is part of its type, and once declared, it cannot be resized.
package main
import "fmt"
func main() {
// Declare an array of integers with a fixed size of 5
var intArray [5]int
// Initialize the array
intArray = [5]int{1, 2, 3, 4, 5}
// Access elements
fmt.Println(intArray[2]) // Prints 3
}
Slices
A slice is a lightweight data structure that wraps an array and provides a way to access a portion of that array. Slices are dynamic and can grow or shrink, so they’re more flexible than arrays.
package main
import "fmt"
func main() {
// Declare a slice of integers
var intSlice []int
// Append elements to the slice
intSlice = append(intSlice, 1, 2, 3, 4, 5)
// Access elements
fmt.Println(intSlice[2]) // Prints 3
}
Sorting
Sorting in Go is commonly performed using the sort
package, which provides functions for sorting slices and other data structures.
package main
import (
"fmt"
"sort"
)
func main() {
// Sorting integers
intSlice := []int{4, 2, 7, 1, 9, 3}
fmt.Println("Before sorting:", intSlice)
sort.Ints(intSlice)
fmt.Println("After sorting:", intSlice)
}
You can do that on strings as well.
package main
import (
"fmt"
"sort"
)
func main() {
// Sorting strings
strSlice := []string{"banana", "apple", "orange", "grape"}
fmt.Println("Before sorting:", strSlice)
sort.Strings(strSlice)
fmt.Println("After sorting:", strSlice)
}
Maps
Maps are key-value pairs, where each key must be unique. They provide an efficient way to look up values based on their associated keys.
package main
import "fmt"
func main() {
// Declare and initialize a map
person := map[string]int{
"Alice": 25,
"Bob": 30,
"Charlie": 35,
}
// Access values
fmt.Println(person["Bob"])
}
Structs
Structs allow you to create custom data types by combining variables of different types into a single entity.
package main
import "fmt"
// Define a struct
type Person struct {
Name string
Age int
}
func main() {
// Create an instance of the Person struct
alice := Person{
Name: "Alice",
Age: 25,
}
// Access fields
fmt.Println(alice.Name)
}
Embedding
Struct embedding is a way to achieve composition by including an anonymous field of another type within a struct. This feature allows you to reuse fields and methods from an existing type within a new type.
package main
import "fmt"
type Person struct {
Name string
Age int
}
type Employee struct {
Person // Embedding the Person struct
EmployeeID int
}
func main() {
// Create an instance of the embedded struct
employee := Employee{
Person: Person{Name: "Alice", Age: 25},
EmployeeID: 12345,
}
// Access fields from the embedded struct
fmt.Println("Name:", employee.Name)
fmt.Println("Age:", employee.Age)
fmt.Println("Employee ID:", employee.EmployeeID)
}
Pointers
A pointer is a variable that stores the memory address of another variable. It points to the memory location where the actual value is stored. Pointers in Go allow you to indirectly access the value of a variable and are often used for dynamic memory allocation.
package main
import "fmt"
func main() {
var num int = 42
// Declare a pointer to the variable
var ptr *int = &num
// Access the value through the pointer
fmt.Println("Value:", *ptr) // Prints 42
}
Interfaces
An interface is a type that specifies a set of method signatures. If a type implements all the methods of an interface, it is said to satisfy or implement that interface. Interfaces in Go provide a way to achieve polymorphism and decouple the implementation from the interface definition.
package main
import "fmt"
// Define an interface
type Shape interface {
Area() float64
}
// Implement the interface for a Circle
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func main() {
// Create a Circle instance
circle := Circle{Radius: 5.0}
fmt.Println("Area:", circle.Area()) // => Area: 78.5
}
Code Challenge
Create a simple book inventory system using Go. Define a struct Book with the following fields:
- Title (string)
- Author (string)
- ISBN (string)
- Quantity (int)