【问题标题】:How to remove all the element in the slice with reflect package in Golang?如何使用 Golang 中的反射包删除切片中的所有元素?
【发布时间】:2017-12-06 13:27:06
【问题描述】:

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

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())

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

【问题讨论】:

    标签: pointers go reflection slice


    【解决方案1】:

    请改用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)
    }
    

    https://play.golang.org/p/JNWE0hCsQp

    【讨论】:

      猜你喜欢
      • 2016-09-16
      • 2016-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 2019-02-05
      相关资源
      最近更新 更多