Sobes.tech
Junior

What are the data types in Go?

sobes.tech AI

Answer from AI

In Go, there are four categories of data types:

  1. Basic types - predefined by the compiler.

    • Boolean: bool
    • Numeric:
      • Integer: int, int8, int16, int32, int64, uint, uint8 (byte), uint16, uint32, uint64, uintptr
      • Floating point: float32, float64
      • Complex numbers: complex64, complex128
    • String: string
  2. Aggregate types - collections of fixed size.

    • Arrays: [n]T (where n is size, T is element type)
    • Structs: struct {} (collection of named fields of different types)
  3. Reference types - pointer types, passed by reference, store a pointer to the underlying data.

    • Slices: []T (dynamic array based on an array)
    • Maps: map[K]V (collection of key-value pairs)
    • Pointers: *T (store the address of a variable)
    • Channels: chan T, chan<- T, <-chan T (for synchronization and communication between goroutines)
    • Functions: func(...) (...) (signature of a function)
  4. Interface types - define a set of method signatures implemented by data types.

    • Interfaces: interface{} (empty interface), interface{ methodName(...) ... }

Examples:

// Basic types
var isTrue bool = true
var age int = 30
var price float64 = 19.99
var name string = "Go Gopher"

// Aggregate types
var numbers [5]int = [5]int{1, 2, 3, 4, 5} // Array
type Person struct { // Struct
    Name string
    Age  int
}
var p Person = Person{Name: "Alice", Age: 25}

// Reference types
var slice []int = []int{1, 2, 3}           // Slice
var grades map[string]int = map[string]int{"Alice": 90, "Bob": 85} // Map
var ptr *int = &age                     // Pointer
var dataChan chan int = make(chan int)  // Channel
var myFunc func(int) int = func(x int) int { return x * 2 } // Function

// Interface types
var i interface{} = "anything" // Empty interface
type Shape interface { // Interface
    Area() float64
}