0

Here is my example: http://play.golang.org/p/D608cYqtO5

Basically I want to do this:

theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The purpose of doing this kind of thing 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.
If you just want to check the type, or assert it to use it, you can just do 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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.