Sobes.tech
Junior

What are the main data structures in Go?

sobes.tech AI

Answer from AI

In Go, the following are the main built-in (primitive) and composite data structures:

Built-in:

  • Boolean (bool)
  • Numeric types:
    • Integer types (int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr)
    • Floating-point numbers (float32, float64)
    • Complex numbers (complex64, complex128)
    • Byte (byte - alias for uint8)
    • Rune (rune - alias for int32, represents a Unicode character)
  • Strings (string)

Composite:

  • Arrays (array)
    • Fixed size.
    var arr [5]int // array of 5 integers
    
  • Slices (slice)
    • Dynamic size, based on arrays.
    var s []int // uninitialized slice
    s = make([]int, 5, 10) // slice of length 5 with capacity 10
    
  • Maps (map)
    • Unordered collection of key-value pairs.
    m := make(map[string]int) // map with string keys and int values
    
  • Structs (struct)
    • Typed collection of fields.
    type Person struct {
        Name string
        Age  int
    }
    
  • Pointers (pointer)
    • Store memory address.
    var x int = 10
    var p *int = &x // p points to x
    
  • Functions (func)
    • In Go, functions are first-class types.
    type MyFunc func(int) string // function type
    
  • Channels (channel)
    • Used for synchronization and data exchange between goroutines.
    ch := make(chan int) // unbuffered channel for int
    
  • Interfaces (interface)
    • Represent a set of methods that a type must implement.
    type Reader interface {
        Read(p []byte) (n int, err error)
    }
    

It is also worth mentioning other important composite types such as:

  • Byte slices ([]byte)
  • Rune slices ([]rune)

These data structures provide flexibility and performance for a wide range of tasks in Go.