Created
August 1, 2017 14:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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