Golang if 语句在 int32 中看不到 0

Var*_*orb 1 go protocol-buffers grpc

我有用 golang 编写的 proto3/grpc 函数。有一个写在 switch 中的 if 语句,当值为 0 时,它不会将 int32 视为 0。我之前打印了该值,它是 0,但 if 语句无论如何都会运行。在我下面的代码中,我在评论中有输出。我知道对于 int,nil 值是 0。如果我为 lname、fname 放置一个值,它们会正常工作。任何帮助表示赞赏。这是我的输出:

map[fname: lname: email: id:0]
0
id = $1
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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
    ...
Run Code Online (Sandbox Code Playgroud)

Adr*_*ian 5

因为文字0不是同一种类型。如果你这样做:

if v != int32(0) {
Run Code Online (Sandbox Code Playgroud)

当值为 an 时int32,它按预期工作。不幸的是,您将所有 int 类型组合在一个案例中,这将使正确处理变得困难/笨拙。您可能可以使用反射在运行时使用reflect.Zero将值与其类型的零值进行比较