A
A
ajlhimik2019-07-18 20:08:20
go
ajlhimik, 2019-07-18 20:08:20

How to create a slice from an array without passing it by reference?

arr := [5]float64{1,2,3,4,5}
x := arr[0:5]

when x[2] changes, it will also be equal to 10 and vice versa, but how to create a new slice from the array without a cycle, like thisarr[2] = 10x := arr[0:5]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav, 2019-07-18
@ajlhimik

package main

import (
  "fmt"
)

func main() {
  arr := [5]float64{1, 2, 3, 4, 5}
  i := 3
  x := append([]float64{}, arr[:i]...)
  x[2] = 42
  fmt.Println(x)
  fmt.Println(arr)
}

https://play.golang.org/p/L5jQgS1_M0j
I advise you to read, there are a lot of interesting things about slices https://github.com/golang/go/wiki/SliceTricks

U
uvelichitel, 2019-07-18
@uvelichitel

arr := [5]float64{1,2,3,4,5}
var newslice = make([]float64, 5)
copy(newslice, arr[0:5])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question