Skip to content

Instantly share code, notes, and snippets.

@tiagopotencia
Created August 1, 2017 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagopotencia/8a3ec1d45c7ea902addb3f60a21f10c5 to your computer and use it in GitHub Desktop.
Save tiagopotencia/8a3ec1d45c7ea902addb3f60a21f10c5 to your computer and use it in GitHub Desktop.
Using type assertion we can get the type of an interface{}. Go's already knows that value and says it if you try to make a wrong convertion.
package main
import (
"fmt"
)
func main() {
type interfaceToStringSliceStruct struct {
interfaceToStringSlice interface{}
}
interfaceToStringSliceStrct := interfaceToStringSliceStruct{}
stringSlice := []string{"a", "b"}
interfaceToStringSliceStrct.interfaceToStringSlice = stringSlice
result := convertInterfaceToSliceString(interfaceToStringSliceStrct.interfaceToStringSlice)
fmt.Println("interfaceToStringSliceStrct.interfaceToStringSlice -> ", interfaceToStringSliceStrct.interfaceToStringSlice)
fmt.Println("result -> ", result)
fmt.Println("result[0] -> ", result[0])
fmt.Println("result[1] -> ", result[1])
}
func convertInterfaceToSliceString (interfaceToConvert interface{}) []string{
a := interfaceToConvert.([]string)
fmt.Println("a -> ", a)
return a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment