英文:
Exclude empty fields from struct iteration
问题
我有一个结构体,它将从用户输入中获取其值。
现在我想提取只有关联值的字段名称。值为nil
的字段不应返回。我该如何做到这一点?
以下是我的代码:
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)
}
}
当前结果:
Name
Password
期望结果:
Name
英文:
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
答案1
得分: 5
你需要编写一个函数来检查是否为空:
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
}
英文:
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
}
答案2
得分: 0
我认为我找到了一个解决方案。案件结案。:)
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
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论