Tell about the main data structures in Go.
sobes.tech AI
Answer from AI
In Go, the main data structures include:
-
Arrays — fixed-size sequences of elements of the same type. The size is set at declaration and does not change.
-
Slices — dynamic, more flexible wrappers over arrays. Slices contain a pointer to an array, a length, and a capacity. They allow convenient work with sequences of variable length.
-
Maps — hash tables implementing associative arrays (key-value pairs). Keys and values can be of different types, but keys must be comparable.
-
Structs — user-defined types that group several fields of different types into a single entity.
-
Interfaces — describe a set of methods that a type must implement. They allow working with different types through a common interface.
Example of using a slice and a map:
package main
import "fmt"
func main() {
// Slice
nums := []int{1, 2, 3}
nums = append(nums, 4)
fmt.Println(nums) // [1 2 3 4]
// Map
ages := map[string]int{"Alice": 30, "Bob": 25}
ages["Charlie"] = 35
fmt.Println(ages) // map[Alice:30 Bob:25 Charlie:35]
}