B
B
bozedai2021-01-06 12:06:41
go
bozedai, 2021-01-06 12:06:41

Is it possible to change the length of a slice directly in Golang?

The problem is this: a slice is passed to the function

func foo(bar []int){
    // Как изменить length у среза?
}
input := []int{1, 2, 3}
foo(input)
fmt.Println(len(input)) // Например: 2


And you need to change the length of the slice inside the function without creating a new one, so that everything is available at the old pointer.

So this is not working
*&bar = bar[:2]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Mamonov, 2021-01-06
@bozedai

You can try to do it through reflect, for example like this

package main

import (
    "fmt"
    "reflect"
)

func modify(input *[]int, newLen int) {
    val := reflect.Indirect(reflect.ValueOf(input))
    val.SetLen(newLen)
}

func main() {
    input := []int{1, 2, 3}

    fmt.Printf("Before: %p, value: %v\n", &input, input)

    modify(&input, len(input) - 1)

    fmt.Printf("After: %p, value: %v\n", &input, input)
}

Conclusion:
Before: 0xc00000c060, value: [1 2 3]
After: 0xc00000c060, value: [1 2]

K
Klars, 2021-01-11
@Klars

Another option

package main

import (
  "fmt"
)

func squeeze(sl *[]int, splitter int) {
  s := *sl
  s = s[:splitter]
  *sl = s
}

func main() {
  sl := []int{1, 2, 3, 4, 5, 6}
  fmt.Println(len(sl), cap(sl), sl)
  fmt.Printf("%p\n\n", &sl)

  squeeze(&sl, 4)

  fmt.Println(len(sl), cap(sl), sl)
  fmt.Printf("%p", &sl)
}

output:
6 6 [1 2 3 4 5 6]
0xc00000c0a0
4 6 [1 2 3 4]
0xc00000c0a0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question