Reputation: 997
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
Upvotes: 0
Views: 2483
Reputation: 997
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
Upvotes: 0
Reputation:
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
}
Upvotes: 5