How to initialize a slice with a range of numbers in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// Build a slice using a simple for‑loop.
// This is the most common and flexible approach.
func makeRangeLoop(start, end int) []int {
    size := end - start
    values := make([]int, size) // allocate exact size

    for i := 0; i < size; i++ {
        values[i] = start + i
    }

    return values
}

// Build a slice using append.
// Useful when you want dynamic growth or additional logic.
func makeRangeAppend(start, end int) []int {
    values := []int{}
    for n := start; n < end; n++ {
        values = append(values, n)
    }
    return values
}

// Build a slice using a generator‑style channel.
// This allows streaming values lazily.
func makeRangeChannel(start, end int) []int {
    ch := make(chan int)

    // Produce values in a separate goroutine.
    go func() {
        for n := start; n < end; n++ {
            ch <- n
        }
        close(ch)
    }()

    // Collect values.
    values := []int{}
    for v := range ch {
        values = append(values, v)
    }

    return values
}

// Build a slice using copy into a pre‑allocated buffer.
// Shows how to repurpose an existing slice.
func makeRangeCopy(start, end int) []int {
    size := end - start
    values := make([]int, size)

    for i := range values {
        values[i] = start + i
    }

    return values
}

// Print a slice for demonstration.
func show(label string, values []int) {
    fmt.Printf("%s: %v\n", label, values)
}

func main() {
    a := makeRangeLoop(1, 10)
    b := makeRangeAppend(1, 10)
    c := makeRangeChannel(1, 10)
    d := makeRangeCopy(1, 10)

    show("loop", a)
    show("append", b)
    show("channel", c)
    show("copy", d)
}


/*
run:

loop: [1 2 3 4 5 6 7 8 9]
append: [1 2 3 4 5 6 7 8 9]
channel: [1 2 3 4 5 6 7 8 9]
copy: [1 2 3 4 5 6 7 8 9]

*/

 



answered Aug 18 by avibootz

Related questions

2 answers 400 views
400 views asked Mar 15, 2020 by avibootz
2 answers 386 views
1 answer 285 views
1 answer 255 views
1 answer 299 views
1 answer 237 views
237 views asked Aug 11, 2020 by avibootz
...