# Structs structs 包封装了一个抽象的`Struct`结构体,提供了操作`struct`的相关函数
## 源码: - [https://github.com/duke-git/lancet/blob/main/structs/struct.go](https://github.com/duke-git/lancet/blob/main/structs/struct.go) ## 用法: ```go import ( "github.com/duke-git/lancet/v2/structs" ) ``` ## 目录: - [New](#New) - [ToMap](#ToMap) - [Fields](#Fields) - [Field](#Field) - [IsStruct](#IsStruct) ## API 文档: ### New`Struct`结构体的构造函数
函数签名: ```go func New(value any, tagName ...string) *Struct ``` 示例: ```go package main import ( "github.com/duke-git/lancet/v2/structs" ) func main() { type People struct { Name string `json:"name"` } p1 := &People{Name: "11"} s := structs.New(p1) // to do something } ``` ### ToMap将一个合法的struct对象转换为map[string]any
函数签名: ```go func (s *Struct) ToMap() (map[string]any, error) ``` 除此之外,提供一个便捷的静态方法 ToMap ```go func ToMap(v any) (map[string]any, error) ``` 示例: ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type People struct { Name string `json:"name"` } p1 := &People{Name: "11"} s1 := structs.New(p1) m1, _ := s1.ToMap() fmt.Println(m1) // 如果不需要Struct更多的方法,可以直接使用ToMap m2, _ := structs.ToMap(p1) fmt.Println(m2) // Output: // map[name:11] // map[name:11] } ``` ### Fields获取一个struct对象的属性列表
函数签名: ```go func (s *Struct) Fields() []*Field ``` 示例: ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type People struct { Name string `json:"name"` } p1 := &People{Name: "11"} s := structs.New(p1) fields := s.Fields() fmt.Println(len(fields)) // Output: // 1 } ``` ### Field根据属性名获取一个struct对象的属性
函数签名: ```go func (s *Struct) Field(name string) *Field ``` 示例: ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type People struct { Name string `json:"name"` } p1 := &People{Name: "11"} s := structs.New(p1) f := s.Field("Name") fmt.Println(f.Value()) // Output: // 11 } ``` ### IsStruct判断是否为一个合法的struct对象
函数签名: ```go func (s *Struct) IsStruct() bool ``` 示例: ```go package main import ( "fmt" "github.com/duke-git/lancet/v2/structs" ) func main() { type People struct { Name string `json:"name"` } p1 := &People{Name: "11"} s := structs.New(p1) fmt.Println(s.IsStruct()) // Output: // true } ```