Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
假设我们有一个User类型
User
type User struct { FirstName string LastName string ... }
我需要一个返回[]string字段名称的函数[FirstName, LastName, ...]
[]string
[FirstName, LastName, ...]
这可以使用反射来完成(通过反射包):
instance := struct{Foo string; Bar int }{"foo", 2} v := reflect.ValueOf(instance) names := make([]string, 0, v.NumField()) v.FieldByNameFunc(func(fieldName string) bool{ names = append(names, fieldName) return false })
游戏中的活生生的例子。