Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,846 questions

55,675 answers

573 users

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 6 days ago by avibootz

Related questions

2 answers 302 views
302 views asked Mar 15, 2020 by avibootz
2 answers 298 views
1 answer 214 views
1 answer 192 views
1 answer 229 views
1 answer 185 views
185 views asked Aug 11, 2020 by avibootz
...