Getting type information from name as a string

104 views
Skip to first unread message

in...@marczahn.de

unread,
May 21, 2019, 11:15:03 PM5/21/19
to golang-nuts
Hi,

for a code generator I want to get a type of a string which is passed by an argument by go generate. So I have sth. like "[]int" and now I need to know if it is a slice/rangeable, of type int etc. Is this somehow possible?

I cannot have a predefined map from strings to types because it is supposed to be generic.

Marcin Romaszewicz

unread,
May 21, 2019, 11:25:36 PM5/21/19
to in...@marczahn.de, golang-nuts
That's what the reflect package does,


-- Marcin

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/8d9ca631-8737-4c2d-99dc-bbbc37e334e7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

roger peppe

unread,
May 22, 2019, 2:52:58 AM5/22/19
to in...@marczahn.de, golang-nuts
So you have a string which contains a Go type expression, and you want to find out attributes of that type? In general you can't do that without knowing the context that the expression is to be evaluated in. For example, the string "T" could be any kind of type if T is defined as a type somewhere.

Assuming you know the package that the type expression is in, you could use https://godoc.org/golang.org/x/tools/go/packages to load it up, then use https://golang.org/pkg/go/ast to parse the type expression and use the results of the first to look up symbols from the resulting AST.

  cheers,
    rog.

--

in...@marczahn.de

unread,
May 22, 2019, 3:26:07 PM5/22/19
to golang-nuts
@rog: I guess this could be the answer. I saw it at mockgen later as well. Thank you for that hint.
Reply all
Reply to author
Forward
0 new messages