Trevor V
Trevor V

Reputation: 2141

Golang if statement not seeing 0 for int32

I have proto3/grpc function written in golang. There is a if statement written in a switch that does't see an int32 as a value of 0 when the value is a 0. I print the value before and it's a 0 but the if statement runs anyway. In my code below I have the output in a comment. I know for a int the nil value is a 0. If I place a value for the lname, fname they work as it should. Any help appreciated. Here is my output:

map[fname: lname: email: id:0]
0
id = $1

Here is my code:

func (s *server) GetUsers(ctx context.Context, in *userspb.User) (*userspb.Users, error) {
    flds := make(map[string]interface{})
    flds["id"] = in.Id // 0
    flds["fname"] = in.Fname // "" (empty)
    flds["lname"] = in.Lname // "" (empty)
    flds["email"] = in.Email // "" (empty)

    fmt.Println(flds) //map[lname: email: id:0 fname:]

    var where bytes.Buffer

    n := 0
    for _, v := range flds {
        switch v.(type) {
        case string:
            if v != "" {
                n++
            }
        case int, int32, int64:
            if v != 0 {
                n++
            }
        }
    }

    calledvariables := make([]interface{}, 0)

    i := 1
    for k, v := range flds {

        switch v.(type) {
        case string:
            if v != "" {
                if i != 1 {
                    where.WriteString(" AND ")
                }
                ist := strconv.Itoa(i)
                where.WriteString(k + " = $" + ist)
                calledvariables = append(calledvariables, v)
                i++
            }
        case int, int32, int64, uint32, uint64:
            /////// THIS IF STATMENT IS THE ISSUE the ( v is printing the value of 0 and it's in the if statement )
            if v != 0 {
                fmt.Println(v) // 0
                if i != 1 {
                    where.WriteString(" AND ")
                }
                ist := strconv.Itoa(i)
                where.WriteString(k + " = $" + ist)
                calledvariables = append(calledvariables, v)
                i++
            }
        }
    }

    fmt.Println(where.String()) // id = $1
    ...

Upvotes: 1

Views: 1789

Answers (1)

Adrian
Adrian

Reputation: 46542

Because the literal 0 is not the same type. If you do:

if v != int32(0) {

When the value is an int32, it works as expected. Unfortunately, you're combining all the int types in a single case, which will make this difficult/unwieldy to handle correctly. You could probably work something out using reflection to compare the value against the zero value for its type at runtime, using reflect.Zero.

Upvotes: 5

Related Questions