#where is the list and where is the array ?
26 messages · Page 1 of 1 (latest)
both of them are slice, neither list or array
we don't have list in golang, but slices and arrays
the different between slice and array is that array have a constant length, but slice don't
slice := []int{1,2,3,4}
array := [4]int{1,2,3,4}
staticDerivationArray := [...]int{1,2,3,4}
note that [4]int != [5]int != []int
for arrays
[4]int{1,2}
is same as
[4]int{1,2,0,0} // 0 is the default value of type `int`
[...]int{1,2}
is same as
[2]int{1,2} // the literaly count of element "2" replaced `...`
and if you want to covert an array to a slice
arr := [2]int{}
slice := arr[:]
oky now i understand
so they are all slices and a slice will become an array if it has a constant length
?
an array is constant length
and a slice is dynamic length
it is possible to create a slice from an array
in that case the slice is like a window to the underlying array
the slice can show the whole array or only a part of that array
a slice alway has an underlying array associated with it
I recommend reading this https://go.dev/blog/slices-intro
no, slice will never become an array (|| for more advanced, you can use reflect/unsafe, but it's not recommend ||), but an array is possible to become slice.
you can just cast it to an array and this adds a bound check
array := [42]int(slice)
yes, but that would cause an error if the slice length is not match
yeah
and slice is always changing
but this is dynamically checked
so it's not a recommend operator