5

Is it possible to create variable with type from string?

Example:
 I have two types:

type FirstType struct {
    ...
}

type SecondType struct {
    ...
}

// also I have a string variable
var1 := "Second"

I want to create variable with type - String value + "Type":

var variable = []var1+"Type" // slice of "SecondType"

Expected result is like in this case:

var variable = []SecondType

Thanks!

1 Answer 1

7

This is not possible. Go does not provide functionality to create variables of types that are not known statically. The type of a variable is always known statically. Consider using interfaces instead.

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

4 Comments

Suppose you have an interface IEvent, and a lot of different implementations of it. You can serialize them into the same object with properties Type and Data, but how would you deserialize them without having a very long switch case operation?
@GioGio Try to avoid this sort of situation. One solution is to have a Deserialize() method in the interface implemented by each implemention to deserialize the IEvent in according to its specific type.
I'm confused, do you mean a Deserialize() on the IEvent interface? How can it be called if we don't have an instance of IEvent yet? I might be missing some important detail
@GioGio Ah sorry, I misunderstood. For deserialisation, you could use an array or hash map of decoding functions instead of a switch statement.

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.