Allow the != operator to be used on nil

This commit is contained in:
Elara 2024-06-06 19:09:50 -07:00
parent d5c33f9e5d
commit 849295bb5f

10
expr.go
View File

@ -55,13 +55,17 @@ func (t *Template) performOp(a, b reflect.Value, op ast.Operator) (any, error) {
return nil, ast.PosError(op, "the in operator can only be used on strings, arrays, and slices (got %s and %s)", a.Type(), b.Type())
}
} else if !b.IsValid() {
if op.Value != "==" {
return nil, ast.PosError(op, "invalid operator for nil value (expected ==, got %s)", op.Value)
if op.Value != "==" && op.Value != "!=" {
return nil, ast.PosError(op, "invalid operator for nil value (expected == or !=, got %s)", op.Value)
}
switch a.Kind() {
case reflect.Chan, reflect.Slice, reflect.Map, reflect.Func, reflect.Interface, reflect.Pointer:
return a.IsNil(), nil
if op.Value == "==" {
return a.IsNil(), nil
} else {
return !a.IsNil(), nil
}
default:
return nil, ast.PosError(op, "values of type %s cannot be compared against nil", a.Type())
}