0

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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

default: return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) would also (inefficiently) handle fields that are themselves structs.
Thanks. But, I simplify it lil bit below. :)
Please, use isZero() method from reflect package now. details: stackoverflow.com/a/57613511
0

I think I found a solution. Case closed. :)

import "fmt"
import "reflect"

type Users struct {
    Name string
    Password string
}


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

    val := reflect.ValueOf(u)

    var fFields []string

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

    if f.Interface() != "" {
        fFields = append(fFields, val.Type().Field(i).Name)
    }

    }

   fmt.Println(fFields)
}

http://play.golang.org/p/QVIJaNXGQB

1 Comment

Great--though I'd be inclined to accept 4of4's answer because the question's phrasing covers non-string fields too, and the more general answer could be useful for folks researching this problem later. (It also doesn't "cost" you anything to accept it, so to speak.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.