ProgramGuru

Slice Programs

Start with Slice Programs

Learn slice programs through an executable example, then connect the small demonstration to production code.

What you’ll learn

  • Explain the main purpose of slice programs.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Slices provide flexible views into arrays. Practice filtering, appending, copying and capacity behavior with meaningful collections.

The example builds a new slice containing even values, leaving the original input unchanged.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for example slicesFiltering produces a new selection of values.Input sliceStep 1Test each valueStep 2Append matchesStep 3Return resultStep 4Filtering produces a new selection of values.
Filtering produces a new selection of values.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func filterEven(values []int) []int {
	result := make([]int, 0, len(values))
	for _, n := range values {
		if n%2 == 0 {
			result = append(result, n)
		}
	}
	return result
}
func main() {
	numbers := []int{1, 2, 3, 4, 6}
	fmt.Println("Even:", filterEven(numbers))
	fmt.Println("Original:", numbers)
}

Output

Even: [2 4 6]
Original: [1 2 3 4 6]

Trace what the program does

Each value is tested with remainder by two. The result contains 2, 4 and 6, while the input retains all five values.

Avoid common mistakes

  • Appending to a slice may reuse or replace its backing array depending on capacity.
  • Do not assume an assignment copies all slice elements; use copy or slices.Clone when an independent copy is needed.

Try it yourself

Create a filter for numbers greater than three and compare the original and new slices.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does append return?
Choose one answer. You can try again.

Answer and explanation

A slice value that should be assigned or used

Correct. Each value is tested with remainder by two.

What you should remember

You have practiced Slice Programs in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: String Programs →