Data Types and Slices

Go is a Statically Typed language, which means the type of every variable must be known at compile time. While its basic types (strings, ints, booleans) are standard, its approach to collections—specifically the distinction between Arrays and Slices—is a core part of its performance model.


1. Arrays: Fixed-Size Storage

In Go, an array is a numbered sequence of elements of a specific length.

var scores [5]int // An array of exactly 5 integers

2. Slices: Dynamic Views

A Slice is a much more common and powerful structure. Slices are "Wrappers" or "Descriptors" for arrays.

// A slice header consists of:
type SliceHeader struct {
    Data uintptr // Pointer to the underlying array
    Len  int     // Current number of elements
    Cap  int     // Maximum number of elements before reallocating
}

3. Creating and Growing Slices

nums := []int{1, 2}
nums = append(nums, 3) 

4. Sub-slicing (Slicing the Slice)

You can create a new slice from an existing one using the [start:stop] syntax. Both slices will point to the Same memory location in the underlying array. Changing one will affect the other.

original := []int{0, 1, 2, 3, 4}
view := original[1:3] // [1, 2]
view[0] = 99
fmt.Println(original[1]) // 99!

Interview Pro-Tips: Len vs Cap

If an interviewer asks what happens when you append to a full slice:


Technical Summary

  1. Static Types: Enforced at compile time.
  2. Slice Header: A small struct that points to a large array.
  3. Zero-Value: The zero value for a slice is nil, which has len and cap of 0.