如何将 []reflect.Value() 转换为 []string?

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

How to convert to []reflect.Value() to []string?

问题

我正在尝试将我的映射键映射到一个切片中。我找到了这个看起来很好用的解决方案。

func main() {
  newMap := map[string]bool{
    "a": true,
    "b": true,
    "c": true,
  }

  mappedToSlice := reflect.ValueOf(newMap).MapKeys()

  var convertToSliceString []string
  _ = convertToSliceString
}

这个reflect.ValueOf(newMap).MapKeys()似乎可以将键映射到一个切片中。但是,问题是它返回的是一个类型为[]reflect.Value的值。与此同时,我想将它存储在一个类型为[]string(或任何其他切片类型)的变量中,就像convertToSliceString变量一样。

有没有办法可以做到这一点?我尝试使用interface和寻找其他方法,但似乎没有人能够转换它。

英文:

I'm trying to map my map keys into a slice. I found this solution which seems to be working great.

func main() {
  newMap := map[string]bool{
    "a": true,
    "b": true,
    "c": true,
  }

  mappedToSlice := reflect.ValueOf(newMap).MapKeys()

  var convertToSliceString []string
  _ = convertToSliceString
}

This reflect.ValueOf(newMap).MapKeys() seems to be working on mapping the keys to a slice. But, the problem is that it returns a value with a type of []reflect.Value. Meanwhile, I wanna store it in a type of []string (or any other slice type) just like on the convertToSliceString variable.

Is there any way to do it? I've tried using interface and looking for other methods but no one seems to be able to convert it.

答案1

得分: 1

使用for循环将值字符串分配给切片:

mappedToSlice := reflect.ValueOf(newMap).MapKeys()
convertToSliceString := make([]string, len(mappedToSlice))
for i, v := range mappedToSlice {
    convertToSliceString[i] = v.Interface().(string)
}
英文:

Use a for loop to assign the value strings to a slice:

mappedToSlice := reflect.ValueOf(newMap).MapKeys()
convertToSliceString := make([]string, len(mappedToSlice))
for i, v := range mappedToSlice {
    convertToSliceString[i] = v.Interface().(string)
}

huangapple
  • 本文由 发表于 2022年10月6日 02:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/73964653.html
匿名

发表评论

匿名网友

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

确定