Skip to content

Commit

Permalink
chore: add missing tests for var-declarations, fix any/interface{} ty…
Browse files Browse the repository at this point in the history
…pe issue (#1154)

* chore: add missing tests for var-declarations, fix any/interface{} type issue
  • Loading branch information
denisvmedia authored Dec 2, 2024
1 parent cb74ccb commit dde8344
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
15 changes: 14 additions & 1 deletion rule/var_declarations.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (w *lintVarDeclarations) Visit(node ast.Node) ast.Visitor {
// If the RHS is a isZero value, suggest dropping it.
isZero := false
if lit, ok := rhs.(*ast.BasicLit); ok {
isZero = zeroLiteral[lit.Value]
isZero = isZeroValue(lit.Value, v.Type)
} else if isIdent(rhs, "nil") {
isZero = true
}
Expand Down Expand Up @@ -142,3 +142,16 @@ func validType(t types.Type) bool {
t != types.Typ[types.Invalid] &&
!strings.Contains(t.String(), "invalid type") // good but not foolproof
}

func isZeroValue(litValue string, typ ast.Expr) bool {
switch val := typ.(type) {
case *ast.Ident:
if val.Name == "any" {
return litValue == "nil"
}
case *ast.InterfaceType:
return litValue == "nil"
}

return zeroLiteral[litValue]
}
6 changes: 6 additions & 0 deletions testdata/golint/var_declaration.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,9 @@ var y string = q(1).String() // MATCH /should omit type string from declaration
type q int

func (q) String() string { return "I'm a q" }

// The only true zero value for any/interface{} is nil. Others will be considered non-zero.
var z1 any = 0 // No warning, zero value for any is nil
var z2 any = nil // MATCH /should drop = nil from declaration of var z2; it is the zero value/
var z3 interface{} = 0 // No warning, zero value for any is nil
var z4 interface{} = nil // MATCH /should drop = nil from declaration of var z4; it is the zero value/

0 comments on commit dde8344

Please sign in to comment.