Tutorials Logic, IN info@tutorialslogic.com

Golang Arrays, Slices and Maps: Collections with Examples

Golang Arrays, Slices and Maps

Go has arrays, slices, and maps for working with collections. Arrays have fixed length, slices are flexible views over arrays, and maps store key-value pairs for fast lookup.

Most Go programs use slices more often than arrays. Slices can grow with `append`, can be ranged over, and are passed around as small descriptors pointing to underlying array storage. Maps are ideal when values are found by key, such as user ID, slug, email, or status.

Golang is expanded here with a practical explanation, multiple examples, and beginner-focused checks so the idea is easier to learn from this page alone.

Read the concept first, then trace the example line by line. The important habit is to connect the rule to visible behavior instead of memorizing only the name.

Arrays vs Slices

An array length is part of its type, so `[3]int` and `[4]int` are different types. A slice type like `[]int` is more flexible and can represent any number of integers.

  • Use arrays for fixed-size data where length is part of the model.
  • Use slices for most lists and dynamic collections.
  • `append` may allocate a new underlying array when capacity is exceeded.
  • A slice has length and capacity; length is current items, capacity is available backing storage.

Slice Basics

Slice Basics
package main

import "fmt"

func main() {
	scores := []int{70, 85, 90}
	scores = append(scores, 95)

	for index, score := range scores {
		fmt.Println(index, score)
	}

	fmt.Println("length:", len(scores))
	fmt.Println("capacity:", cap(scores))
}

Maps

A map stores values by key. The key type must be comparable, such as string, int, bool, or a struct made of comparable fields. Maps are reference-like values, so changes through one map variable are visible through another variable pointing to the same map.

  • Create maps with a literal or with `make`.
  • Use comma-ok lookup to distinguish missing keys from zero values.
  • Delete entries with `delete(mapValue, key)`.
  • Map iteration order is intentionally not guaranteed.

Map Lookup

Map Lookup
package main

import "fmt"

func main() {
	stock := map[string]int{
		"keyboard": 10,
		"mouse":    0,
	}

	quantity, ok := stock["mouse"]
	if ok {
		fmt.Println("mouse quantity:", quantity)
	}

	if _, ok := stock["monitor"]; !ok {
		fmt.Println("monitor is not in the map")
	}
}

Collection Design Tips

Choose slices when order matters, duplicates are allowed, or you need to process every item. Choose maps when lookup by key is the main operation.

  • Use a slice of structs for ordered records.
  • Use a map for fast lookup by ID or name.
  • Combine both when you need stable order and fast lookup.
  • Avoid modifying a slice while ranging over it unless the behavior is deliberate and tested.

Detailed Explanation of Golang

Golang becomes much easier when you separate the concept from the tool syntax. First identify the problem being solved, then identify the data or resource being changed, and finally identify the proof that the change worked.

In Golang, this topic should be studied through explicit types, readable control flow, error returns, package boundaries, and small tests. Those points explain not only how to use the feature, but also why it fails when the wrong assumption is made.

The previous audit note was: under 650 content words . This expanded section adds a fuller explanation, concrete examples, and practice guidance so the page can stand on its own for beginners.

A good way to learn this page is to read the normal path once, run or trace the example, then intentionally change one input to observe the different result. That one change teaches more than memorizing several definitions.

  • Write the goal of Golang before touching code or configuration.
  • Identify the normal case, edge case, and failure case.
  • Trace what changes before and after the operation.
  • Use a command, output, compiler message, log, metric, or table to verify the result.
  • Record the mistake that would confuse a beginner and the exact fix.

Beginner-Friendly Walkthrough for Golang

Start with a tiny project scenario. For example, imagine one user action, one request, one resource, one function call, or one batch of data. Keep the scenario small enough that every step can be explained without skipping details.

Next, describe the movement of information. Where does the input start? Which rule or component handles it? What result should appear? If the result is wrong, where would you inspect first?

Finally, compare two outcomes. The correct outcome proves that you understand the main rule. The incorrect outcome teaches the symptom, which is what you will recognize later during debugging or interviews.

  • Normal path: valid input produces the expected result.
  • Boundary path: the smallest, largest, empty, or unusual input still behaves predictably.
  • Error path: a realistic mistake creates a visible symptom.
  • Fix path: one focused correction removes the symptom without changing unrelated code.

Slice Plus Map Index

Slice Plus Map Index
type Product struct {
	ID    int
	Name  string
	Price int
}

products := []Product{
	{ID: 1, Name: "Keyboard", Price: 1200},
	{ID: 2, Name: "Mouse", Price: 500},
}

byID := make(map[int]Product)
for _, product := range products {
	byID[product.ID] = product
}

Golang complete Go practice example

Golang complete Go practice example
package main

import "fmt"

func explainGolang(values []int) {
    for index, value := range values {
        fmt.Printf("Golang step %d has value %d\n", index+1, value)
    }
}

func main() {
    explainGolang([]int{1, 3, 5})
}

Golang Go edge-case example

Golang Go edge-case example
package main

import "errors"

func validateGolang(items []string) error {
    if len(items) == 0 {
        return errors.New("Golang: at least one item is required")
    }
    return nil
}
Key Takeaways
  • Use slices for dynamic ordered lists.
  • Use maps for key-based lookup.
  • Use comma-ok map lookup when zero values are meaningful.
  • Remember that map iteration order is not stable.
  • Explain the purpose of Golang in your own words.
  • Run or trace a small Golang example for Golang.
  • Test a normal case, a boundary case, and a broken case.
  • Verify the result with visible output, logs, metrics, compiler feedback, or a table.
  • Summarize the common mistake and the correction.
Common Mistakes to Avoid
WRONG Expect map iteration to be sorted.
RIGHT Collect keys and sort them when order matters.
Go randomizes map iteration behavior.
WRONG Ignore slice capacity behavior.
RIGHT Understand append may create a new backing array.
This matters when multiple slices share storage.
WRONG Learning Golang only as a term.
RIGHT Learn it through a working example, a boundary case, and a failure case.
Concept plus behavior is easier to remember than definition alone.
WRONG Skipping verification.
RIGHT Always check output, state, logs, metrics, query results, or compiler feedback.
Verification turns confidence into evidence.
WRONG Changing many things at once while debugging.
RIGHT Change one setting, input, or line, then inspect the result.
Small changes reveal the real cause.

Practice Tasks

  • Create a slice of products and calculate the total price.
  • Build a map from product ID to product.
  • Write a function that returns sorted map keys.
  • Create a small demo that shows Golang clearly.
  • Add one edge case and write the expected result before running it.
  • Break the demo intentionally and document the error symptom.
  • Fix the broken version and explain why the fix works.

Frequently Asked Questions

Slices are flexible and work for most dynamic lists. Arrays are fixed-size and less common in everyday Go code.

No. Map keys must be comparable, and slices are not comparable.

Start with one tiny example, trace every step, then compare it with a broken version.

Verify the visible result: output, state, log entry, metric, query result, compiler feedback, or rendered behavior.

It often combines vocabulary with behavior. The confusion drops when you trace the input, rule, result, and failure path.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.