Go, commonly referred to as Golang, is a statically typed, compiled programming language known for its simplicity and efficiency. Composite types are one of the fundamental building blocks in Go used to build complex data structures.
Basic Composite Types in Go
Go provides a few basic composite types:
- Arrays - A fixed-length list of elements of the same type.
- Slices - A flexible and dynamic view into the arrays.
- Maps - A collection of unique keys with values.
- Structs - A collection of fields grouped together, similar to classes in other languages.
Arrays
Arrays in Go have a fixed size. Here is an example of how to declare and initialize an array:
// Go
package main
import "fmt"
func main() {
var numbers [3]int // Declare an array of type int with length 3
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
fmt.Println(numbers)
}Slices
Slices are more powerful than arrays and provide more flexibility:
// Go
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5} // Slice of integers
fmt.Println(numbers)
numbers = append(numbers, 6) // Append value to slice
fmt.Println(numbers)
}Slices are essentially a reference to an array; hence, they are dynamic in nature.
Maps
Maps are used to create a collection that can associate keys with values. Unlike arrays, keys in maps are unique:
// Go
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30}
fmt.Println(ages)
ages["Charlie"] = 35 // Add new key-value pair to a map
fmt.Println(ages)
}Structs
Structs are useful when you want to group together properties that represent an entity:
// Go
package main
import "fmt"
// Define a 'Person' struct
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
fmt.Println(p)
p.Age = 26 // Update the field value
fmt.Println(p)
}Intermediate: Nested Composite Types
You can nest composite types to create more complex data structures:
// Go
package main
import "fmt"
type Company struct {
Name string
Employees map[int]Person // Map of Person structs
}
func main() {
emp := map[int]Person{
1: {Name: "Alice", Age: 25},
2: {Name: "Bob", Age: 30},
}
comp := Company{Name: "Tech Co", Employees: emp}
fmt.Println(comp)
}Advanced: Composite Types with Methods
In Go, you can define methods on composite types such as structs:
// Go
package main
import "fmt"
// Define a struct
type Person struct {
Name string
Age int
}
// Add a method to the Person struct
type Printer interface {
Print()
}
func (p Person) Print() {
fmt.Printf("%s is %d years old\n", p.Name, p.Age)
}
func main() {
p := Person{Name: "Alice", Age: 25}
var pr Printer = p
pr.Print()
}Methods in Go provide a way to define behavior for composite types.
In summary, Go's composite types give you a variety of ways to combine different types of data together, offering a powerful tool for code organization and flexibility.