1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00
Files
lancet/docs/structs/struct_zh-CN.md
zm 5e66bc6227 [structs] change package structutil to structs (#81)
* refactor package structutil to structs

* add structs package zh-CN docs
2023-03-15 19:14:19 +08:00

3.0 KiB
Raw Blame History

Structs

structs 包封装了一个抽象的Struct结构体,提供了操作struct的相关函数

源码:

用法:

import (
    "github.com/duke-git/lancet/v2/structs"
)

目录:

API 文档:

New

`Struct`结构体的构造函数

函数签名:

func New(value any, tagName ...string) *Struct

示例:

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

函数签名:

func (s *Struct) ToMap() (map[string]any, error)

除此之外提供一个便捷的静态方法ToMap

func ToMap(v any) (map[string]any, error)

示例:

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对象的属性列表

函数签名:

func (s *Struct) Fields() []*Field

示例:

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对象的属性

函数签名:

func (s *Struct) Field(name string) *Field

示例:

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对象

函数签名:

func (s *Struct) IsStruct() bool

示例:

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
}