Is it possible to initialize slice with specific values?
Asked Answered
P

2

92

Is it possible to initialize an slice with all 1's like in python?

PYTHON:

onesArray = np.ones(5)
onesList = [1]*5

GOLANG

onesSlice := make([]int, 5)
for i:= 0; i < len(onesSlice); i++{
    onesSlice[i] = 1
}

Is it possible to do better than this?

Performative answered 11/10, 2016 at 19:13 Comment(0)
A
129

Yes but you have to use a different syntax.

oneSlice := []int{1, 1, 1, 1, 1}

It's referred to as 'composite literal'

Also, if there is reason to iterate (like calculating the values based loop variable or something) then you could use the range keyword rather than the old school for i is equal to, i is less than, i++ loop.

for i := range onesSlice {
    onesSlice[i] = 1
}
Almira answered 11/10, 2016 at 19:15 Comment(3)
len(oneSlice) == cap(oneSlice)Ruhnke
I want to create a slice containing n copies of integer val. Is there an easier way than looping? For example, in C++ I can do vector<int> a(n, val).Clay
There is no easy way in Go as of 1.16. It would be nice if you could write eg make_init([]int, N, INIT_VAL) could create a slice of N times INIT_VAL (with capacity N).Diggins
S
3

Starting with Go 1.23 which will be released in August 2024, there will be a special function Repeat() in the slices package, so the code would be like this:

onesArray := slices.Repeat([]int{1}, 5)

This code will solve the problem according to Adam Jones' proposal which was accepted a month ago.

Sam answered 14/4 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.