Home > Software design >  How to convert to []reflect.Value() to []string?
How to convert to []reflect.Value() to []string?

Time:10-06

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.

CodePudding user response:

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)
}
  •  Tags:  
  • go
  • Related