英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论