Pointers 如何使用Golang中的reflect包删除切片中的所有元素?

Pointers 如何使用Golang中的reflect包删除切片中的所有元素?,pointers,go,reflection,slice,Pointers,Go,Reflection,Slice,我正在尝试创建一个函数,可以像这样重置传递的切片: func resetSlice(slice interface{}) { v := reflect.ValueOf(slice) s := v.Type().Elem() // QUESTION: How to reset the slice here? } usernames := []string{"Hello", "World"} resetSlice(&usernames) fmt.Println(

我正在尝试创建一个函数,可以像这样重置传递的切片:

func resetSlice(slice interface{}) {
    v := reflect.ValueOf(slice)
    s := v.Type().Elem() 
    // QUESTION: How to reset the slice here?
}

usernames := []string{"Hello", "World"}
resetSlice(&usernames)

fmt.Println(usernames) // OUTPUT  : [Hello World]
                       // EXPECTED: []
但我不知道如何重置指针片。可以创建一个新的切片,该切片的类型与指针切片的类型相同

reflect.New(v.Type().Elem())

然后替换指针片?但是怎么做呢?

使用
reflect.MakeSlice

package main

import (
    "fmt"
    "reflect"
)

func resetSlice(slice interface{}) {
    v := reflect.ValueOf(slice)
    v.Elem().Set(reflect.MakeSlice(v.Type().Elem(), 0, v.Elem().Cap()))
}


func main() {
    a := []string{"foo", "bar", "baz"}  
    resetSlice(&a)
    fmt.Println(a)
}

改用
reflect.MakeSlice

package main

import (
    "fmt"
    "reflect"
)

func resetSlice(slice interface{}) {
    v := reflect.ValueOf(slice)
    v.Elem().Set(reflect.MakeSlice(v.Type().Elem(), 0, v.Elem().Cap()))
}


func main() {
    a := []string{"foo", "bar", "baz"}  
    resetSlice(&a)
    fmt.Println(a)
}