I am trying to set structs dynamically by a variable. Is this possible?
package main
import "fmt"
type Vertex struct {
X int
Y int
}
struct :="Vertex"
func main() {
fmt.Println(struct{1, 2})
}
TIA!
I am trying to set structs dynamically by a variable. Is this possible?
package main
import "fmt"
type Vertex struct {
X int
Y int
}
struct :="Vertex"
func main() {
fmt.Println(struct{1, 2})
}
TIA!
What exactly you are trying to do? Type above is Vertex
, not struct
:
fmt.Println(Vertex{1, 2})
I am trying to fetch structs using a dynamic variable.
Maybe implement a factory or something could be a better idea or do something like
package main
import (
"fmt"
)
type Vertex struct {
X int
Y int
}
func toStruct(st string) interface{} {
if st == "Vertex" {
return Vertex{}
}
return nil
}
func main() {
s := "Vertex"
st := toStruct(s)
fmt.Printf("%T", st)
//fmt.Println(s{1, 2})
}
In general, such a thing is not possible, as you might pass in a struct
value that would lead to a struct with a different set of fields. Though creation of struct literals has to be decidable at compiletime.
I do not think I can pass text and get a struct. Or have I missed something?
“general” sounds to me that there is a tiny chance?
Not in gos typesystem, except for using a dispatch mechanism as described by @Yamil_Bracho.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.