Here is my example: http://play.golang.org/p/D608cYqtO5
Basically I want to do this:
theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)
Here is my example: http://play.golang.org/p/D608cYqtO5
Basically I want to do this:
theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)
The notation
value.(type)
is called a type-assertion. The type
in an assertion has to be known at compile-time and it's always a type name.
In your playground example SetStruct2
could use a type-switch to handle different types for its second argument:
switch v := value.(type) {
case Config:
// code that uses v as a Config
case int:
// code that uses v as an int
}
You cannot, however, assert an interface to be something dynamic (like in your code). Because otherwise the compiler could not type-check your program.
Edit:
I don't want to case them one by one if there is another way to do so?
You can use reflection to work type-agnostically. You can then set stuff randomly on values but it will panic if you perform an illegal operation for a type.
If you want to benefit from the compiler's type checks you'll have to enumerate the different cases.