douquqiang1513 2014-12-01 05:07
浏览 32
已采纳

从结构迭代中排除空字段

I have a struct that will get its value from user input. Now I want to extract only field names that have associated values. Fields with a nil value should not be returned. How can I do that?

Here’s my code:

package main


import "fmt"
import "reflect"

type Users struct {
    Name string
    Password string
}


func main(){
    u := Users{"Robert", ""}

    val := reflect.ValueOf(u)


    for i := 0; i < val.NumField(); i++ {

        fmt.Println(val.Type().Field(i).Name)

    }


} 

Current Result:

Name
Password

Expected result:

Name
  • 写回答

2条回答 默认 最新

  • dongshan8953 2014-12-01 06:09
    关注

    You need to write a function to check for empty:

    func empty(v reflect.Value) bool {
        switch v.Kind() {
        case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
            return v.Int() == 0
        case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
            return v.Uint() == 0
        case reflect.String:
            return v.String() == ""
        case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface, reflect.Chan:
            return v.IsNil()
        case reflect.Bool:
            return !v.Bool()
        }
        return false
    }
    

    playground example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?