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

huangapple go评论104阅读模式
英文:

How to remove all the element in the slice with reflect package in Golang?

问题

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

  1. func resetSlice(slice interface{}) {
  2. v := reflect.ValueOf(slice)
  3. s := v.Type().Elem()
  4. // 问题:如何在这里重置切片?
  5. }
  6. usernames := []string{"Hello", "World"}
  7. resetSlice(&usernames)
  8. fmt.Println(usernames) // 输出:[Hello World]
  9. // 期望:[]

但是我不知道如何重置指针切片。也许可以创建一个与指针切片具有相同类型的新切片,使用 reflect.New(v.Type().Elem()),然后替换指针切片?但是如何实现呢?

英文:

I'm trying to create a function that can reset a passed slice like this:

  1. func resetSlice(slice interface{}) {
  2. v := reflect.ValueOf(slice)
  3. s := v.Type().Elem()
  4. // QUESTION: How to reset the slice here?
  5. }
  6. usernames := []string{"Hello", "World"}
  7. resetSlice(&usernames)
  8. fmt.Println(usernames) // OUTPUT : [Hello World]
  9. // EXPECTED: []

But I have no idea about how to reset a pointer slice. Maybe create a new slice which has the same type as the pointer slice with

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

then replace the the pointer slice? But how?

答案1

得分: 4

使用reflect.MakeSlice代替。

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func resetSlice(slice interface{}) {
  7. v := reflect.ValueOf(slice)
  8. v.Elem().Set(reflect.MakeSlice(v.Type().Elem(), 0, v.Elem().Cap()))
  9. }
  10. func main() {
  11. a := []string{"foo", "bar", "baz"}
  12. resetSlice(&a)
  13. fmt.Println(a)
  14. }

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

英文:

use reflect.MakeSlice instead.

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func resetSlice(slice interface{}) {
  7. v := reflect.ValueOf(slice)
  8. v.Elem().Set(reflect.MakeSlice(v.Type().Elem(), 0, v.Elem().Cap()))
  9. }
  10. func main() {
  11. a := []string{"foo", "bar", "baz"}
  12. resetSlice(&a)
  13. fmt.Println(a)
  14. }

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

huangapple
  • 本文由 发表于 2017年7月3日 18:05:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/44882827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定