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?
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With