DEV Community

Huseyn
Huseyn

Posted on

Make() in GO

What Does make Do in Go?
The make function is used to create and initialize only three types of built-in data structures in Go:

  • ✅ Slices
  • ✅ Maps
  • ✅ Channels

These are reference types, and unlike arrays or structs, they need some internal setup to work properly. The make function does exactly that — it sets them up so you can use them safely.

Why Not Just Declare Normally?
Because if you just declare a slice/map/channel without using make, it may be nil — and using a nil map or channel will cause a runtime error.

Syntax

make(type, length[, capacity])
Enter fullscreen mode Exit fullscreen mode
  • For slices, you can give both length and capacity.
  • For maps, you can give an optional initial capacity.
  • For channels, you specify the buffer size (for buffered channels).

🔍 Examples

  1. 🧺 Slice Example
s := make([]int, 3, 5)
fmt.Println(s)        // [0 0 0]
fmt.Println(len(s))   // 3
fmt.Println(cap(s))   // 5
Enter fullscreen mode Exit fullscreen mode
  • len = how many items it holds now
  • cap = how many items it can hold before resizing

You can now safely use s and append more items.

  1. 🗺️ Map Example
m := make(map[string]int)
m["apple"] = 10
fmt.Println(m) // map[apple:10]
Enter fullscreen mode Exit fullscreen mode

You must use make for maps before writing to them, or you’ll get a panic.

You can give an initial capacity: make(map[string]int, 100) — this allocates space for ~100 items.

  1. 📬 Channel Example
ch := make(chan int, 2)
ch <- 1
ch <- 2
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
Enter fullscreen mode Exit fullscreen mode

This is a buffered channel of size 2.
make is always used to create channels.

❓ What's the Difference Between make and new?

Feature make new
Works with Only slices, maps, channels All types
Returns Initialized value Pointer to zero value
Ready to use? ✅ Yes ❌ No — you often must set it up manually

🧑‍🍳 Real-World Analogy
Imagine you're setting a table:

  • new just gives you an empty plate, but you still need to put food on it.
  • make gives you a fully served plate, ready to eat from.

🧪 In Practice: Shopping Cart

func main() {
    cart := make([]string, 0) // slice
    prices := make(map[string]float64) // map
    orderQueue := make(chan string, 2) // channel

    cart = append(cart, "Book", "Pen")
    prices["Book"] = 9.99

    orderQueue <- "Order #1"
    orderQueue <- "Order #2"

    fmt.Println("Cart:", cart)
    fmt.Println("Price of Book:", prices["Book"])
    fmt.Println("Processing:", <-orderQueue)
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)