Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to initialize slice with specific values?

Tags:

slice

go

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?

like image 677
Nicky Feller Avatar asked Oct 11 '16 19:10

Nicky Feller


People also ask

How do I assign a value to a slice in Golang?

Go slice make function It allocates an underlying array with size equal to the given capacity, and returns a slice that refers to that array. We create a slice of integer having size 5 with the make function. Initially, the elements of the slice are all zeros. We then assign new values to the slice elements.

How do I initialize a list in Golang?

You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.

What is the difference between array and slice?

The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.


1 Answers

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 } 
like image 177
evanmcdonnal Avatar answered Sep 20 '22 07:09

evanmcdonnal