get Package from types.Type

107 views
Skip to first unread message

Randall O'Reilly

unread,
Feb 16, 2019, 2:51:31 AM2/16/19
to golang-nuts
I’m probably missing something very basic, but I have a go/types.Type and I want to find which package it was defined in. I can get the path of the Package using TypeString but somehow I can’t seem to figure out how to get the *Package itself! I can’t find a “lookup package by path” and LookupParent or my own attempt to crawl the Scope() hierarchy up and down doesn’t seem to be working.. Thanks,

- Randy

Randall O'Reilly

unread,
Feb 16, 2019, 3:55:27 AM2/16/19
to golang-nuts
nevermind - I think I figured it out — just need to drill down Underlying until you find types.Named and get the Obj().Pkg() from that. Only Named types have a package home..

- Randy

Paul Jolly

unread,
Feb 16, 2019, 4:06:21 AM2/16/19
to Randall O'Reilly, golang-nuts
Underlying is the identity function for all types except *types.Named
(https://github.com/golang/example/tree/master/gotypes#named-types),
so this won't get you what you want.

Instead what I think you're after is type asserting against the
types.Type you have
(https://github.com/golang/example/tree/master/gotypes#types):

Type = *Basic
| *Pointer
| *Array
| *Slice
| *Map
| *Chan
| *Struct
| *Tuple
| *Signature
| *Named
| *Interface

Then walking "inside" the respective type as required. For example,
you'll probably want to dereference a *types.Pointer via Elem(),
similarly for a slice. For a map you potentially have a more complex
decision with two types!


Paul
> --
> 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.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages