nikolai shytyk
nikolai shytyk

Reputation: 327

Golang, variable with type from string

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!

Upvotes: 5

Views: 1389

Answers (1)

fuz
fuz

Reputation: 93127

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.

Upvotes: 7

Related Questions