-2

i was doing some practicing on go slices and came across a sceneraio where a slice variable got casted to an integer .

package main

import "fmt"

func main() {
    var sli []int

    numbers := [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    fmt.Println(sli == nil)
    sli = numbers[2:4]
    numbers[5] = 100
    fmt.Println(sli, len(sli), cap(sli))
    news := append(sli, 500, 500)

    fmt.Println(news)
    fmt.Println(sli)
    fmt.Println(numbers)
    n2 := copy(sli, news)

    fmt.Println(n2)
}

the n variable prints 2 insead of [2] or anything of that tells it's a slice . here is goplay ground link https://play.golang.org/p/2Ym9RLX1eo_8

  • 2
    See [How does the copy function work?](https://stackoverflow.com/questions/32642907/how-does-the-copy-function-work/32645098?r=SearchResults#32645098) – icza May 10 '21 at 22:47

1 Answers1

5

https://golang.org/pkg/builtin/#copy

Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

sli = numbers[2:4] - so sli has a length of 2.

dave
  • 62,300
  • 5
  • 72
  • 93