Intellij Idea 如何通过GoFunctionDeclaration获取GoStructType对象,goland创意插件

hpcdzsge  于 2023-08-03  发布在  Go
关注(0)|答案(1)|浏览(133)
type SiteInfo struct {
    id int64
}

type SiteResult struct {
    id int64
}

func test(info *SiteInfo) *SiteResult{
    return nil
}

字符串
我想获取param & return struct(可能是GoStructType.class)。获取所有字段。
例如:获取SiteInfo的所有字段。
部分代码

public class TransformAction extends AnAction {

    private Project project;

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {

        // offset is current offset
        PsiElement psiElement = PsiUtilCore.getElementAtOffset(psiFile, offset);
        GoFunctionDeclaration func = PsiTreeUtil.getParentOfType(psiElement, GoFunctionDeclaration.class);
        GoSignature signature = func.getSignature();
        signature.getResultType();// how to get GoStructType.class
        signature.getParameters(); // how to get GoStructType.class

   }
}

gk7wooem

gk7wooem1#

简短的回答是
第一个月
详细的答案是signature.getResultType()得到了GoPointerType,它是一个指向类型引用的指针(而不是类型本身)。你需要解开并解决它。
1.展开指针并获取其基类型引用GoType typeRef =((GoPointerType)signature.getResultType()).getType()
1.解析类型引用GoTypeSpec typeSpec = (GoTypeSpec)typeRef.resolve(signature);
1.从类型规范GoStructType structType = (GoStructType)typeSpec.getSpecType().getType();中获取类型
参数也是如此

for (GoParamDefinition paramDef : signature.getParameters().getDefinitionList()) {
  GoType paramType = paramDef.getGoType(null);
  GoStructType structType = (GoStructType)GoTypeUtil.findTypeSpec(paramType, signature, true).getSpecType().getType();
}

字符串
也可以获取指针基类型的底层类型,在您的情况下,它将返回相同的结果:

GoStructType structType = (GoStructType)GoTypeUtil.unwrapPointerAndParTypes(signature.getResultType())
  .getUnderlyingType(signature)

相关问题