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.
value.(type) is I might have many struct like Config1 ... Config100, I don't want to case them one by one if there is another way to do so.val, ok := value.(TypeICareAbout). This can be fairly useful for doing things like checking what kind of error an error "actually" is, if it implements a package specific interface, so that you can use behavior it exposes (i.e. dave.cheney.net/2014/12/24/inspecting-errors).