Answer the question
In order to leave comments, you need to log in
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
*&bar = bar[:2]
Answer the question
In order to leave comments, you need to log in
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)
}
Before: 0xc00000c060, value: [1 2 3]
After: 0xc00000c060, value: [1 2]
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)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question