From 856f21083e814176f9584cdb3d5df4cfdffc4834 Mon Sep 17 00:00:00 2001 From: Teddy Wing Date: Sat, 20 May 2023 20:58:49 +0200 Subject: Get error variable names from type loop Store the index where we find the `error` type in the function signature's return list so we can use it later to get the corresponding variable names, if any. --- defererr.go | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'defererr.go') diff --git a/defererr.go b/defererr.go index c7816e9..338f2c1 100644 --- a/defererr.go +++ b/defererr.go @@ -36,12 +36,8 @@ func run(pass *analysis.Pass) (interface{}, error) { } funcReturnsError := false - for _, returnVal := range funcDecl.Type.Results.List { - fmt.Printf("returnVal: %#v\n", returnVal) - for _, ident := range returnVal.Names { - fmt.Printf("returnVal name: %#v\n", ident) - } - + errorReturnIndex := -1 + for i, returnVal := range funcDecl.Type.Results.List { fmt.Printf("returnVal Type: %#v\n", returnVal.Type) returnIdent, ok := returnVal.Type.(*ast.Ident) @@ -51,6 +47,7 @@ func run(pass *analysis.Pass) (interface{}, error) { if returnIdent.Name == "error" { funcReturnsError = true + errorReturnIndex = i } } @@ -58,10 +55,14 @@ func run(pass *analysis.Pass) (interface{}, error) { // for _, returnVal := range funcType.Results.List { // } - if !funcReturnsError { + if !funcReturnsError || errorReturnIndex == -1 { return true } + if len(funcDecl.Type.Results.List[errorReturnIndex].Names) > 0 { + fmt.Printf("return error var name: %#v\n", funcDecl.Type.Results.List[errorReturnIndex].Names[0]) + } + ast.Inspect( funcDecl.Body, func(node ast.Node) bool { -- cgit v1.2.3