Chapter 20: In-Memory Store
20.1 The Map (Hash Table)
We need a way to find a Book by its ID instantly. In Computer Science, this is a Hash Map (or Dictionary).
go
var storage = make(map[string]Book)Anatomy of the Declaration
var: Create a variable.make: Crucial Keyword. Maps must be initialized before use.- If you just did
var m map[string]int, it isnil. Writing to it causes a Panic (Crash). makeallocates the memory bucket for the map.
- If you just did
map: The type.[string]: The Key Type (The ID is a string).Book: The Value Type (The full Book struct).
20.2 Pointers vs Values (*Book vs Book)
This is the hardest concept for beginners coming from Python/JS.
go
func GetBook() *Book // Returns a Pointer (Address)
func GetBook() Book // Returns a Value (Photocopy)The Metaphor
- Value (
Book): You ask for the Mona Lisa. I take a Photocopy and hand it to you. If you draw a mustache on the copy, the real Mona Lisa is unchanged. - Pointer (
*Book): You ask for the Mona Lisa. I write "Room 303, Wall 2" on a card and hand it to you. If you go there and draw a mustache, the real painting is changed forever.
Why use Pointers?
- Performance: Copying a huge book is slow. Passing a small address card is fast.
- Mutability: We want to modify the original (e.g., updating the price).
Comparison: Memory
| Language | Default Behavior |
|---|---|
| Python | Everything is a Reference (Pointer-like). |
| Java | Objects are References. Primitives (int) are Values. |
| Go | Everything is a Value (Copy) by default. You must explicitly ask for a Pointer (*). |
🎓 Knowledge Check: If I pass a Book (not *Book) to a function and change its title, what happens to the original book?
Answer: Nothing! You only changed the photocopy. The original book remains untouched. To change the original, you must pass a Pointer (*Book).
