#where is the list and where is the array ?

26 messages · Page 1 of 1 (latest)

sour pasture
#
package main 

import "fmt"

func main(){
    str := make([]int, 2,3) //?

    str[0] = 32
    str[1] = 43

    another := []int{1,2,3,4}//?

    fmt.Println(str)
    fmt.Println(another)
}

i am confused between them

left thorn
#

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[:]
sour pasture
#

oky now i understand

#

so they are all slices and a slice will become an array if it has a constant length

#

?

rocky flicker
#

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

hot surge
left thorn
frozen moon
#

array := [42]int(slice)

left thorn
#

yes, but that would cause an error if the slice length is not match

frozen moon
#

yeah

left thorn
#

and slice is always changing

frozen moon
#

but this is dynamically checked

left thorn
#

so it's not a recommend operator

frozen moon
#

not really

#

it's as bad as the index operator