goslicecapacity

How to initialize slice with initial values and capacity at the same time?


some code is as follow:

const ESTIMATEDSIZE = 10000
var init_arr = [...]int{1,1,2,3,5,8,13}
var fibbo []int = make([]int, len(init_arr), ESTIMATEDSIZE)    
}

There is no reserved function like vector in c++ for slice fibbo to reserve ESTIMATEDSIZE for a slice to reduce the copy time on extending capacity. So I can only assign ESTIMATEDSIZE to capacity at initialization. But neither of below is legal.

var fibbo []int = init_arr[::ESTIMATEDSIZE]
var fibbo []int = make([]int{1,1,2,3,5,8,13}, len(init_arr), ESTIMATEDSIZE)

Are there any method to this question? Or may be the clumsy code as follow is the only way?

var fibbo []int = make([]int, len(init_arr), ESTIMATEDSIZE) 
for i:= range init_arr {
    fibbo[i] = init_arr[i]
}

Solution

  • No, this cannot be done. And it's part of the Go design philosophy that informs this design decision: "Don't hide complexity."

    Your "clumsy" code is actually the preferred and idiomatic way to do this in Go, with one minor change:

    var fibbo = make([]int, len(init_arr), ESTIMATEDSIZE) 
    for i := range init_arr {
        fibbo[i] = init_arr[i]
    }
    

    (Other than formatting), the only change I made was to remove the type from the var declaration, since that's entirely superflous. In other words:

    -var fibbo []int = make([]int, len(init_arr), ESTIMATEDSIZE) 
    +var fibbo = make([]int, len(init_arr), ESTIMATEDSIZE) 
    

    As pointed out in comments, you can also use the copy built-in to eliminate the for loop, if you're not doing any other alterations on the inputs:

    var fibbo = make([]int, len(init_arr), ESTIMATEDSIZE)
    copy(fibbo, init_arr)