Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang, variable with type from string

Tags:

go

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!

like image 485
nikolai-s Avatar asked Mar 18 '23 02:03

nikolai-s


1 Answers

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.

like image 174
fuz Avatar answered Mar 27 '23 20:03

fuz