func foo(bar []int){
// Как изменить length у среза?
}
input := []int{1, 2, 3}
foo(input)
fmt.Println(len(input)) // Например: 2
*&bar = bar[:2]
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]
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)
}