Files
lancet/docs/structs/struct.md
2023-06-15 10:13:27 +08:00

3.1 KiB

Structs

Struct is abstract struct for provide several high level functions

Source:

Usage:

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

Index:

Documentation:

New

The constructor function of the `Struct`

Signature:

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

Example:

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

convert a valid struct to a map

Signature:

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

In addition, provided a convenient static function ToMap

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

Example:

package main

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

func main() {
    type People struct {
        Name string `json:"name"`
    }
    p1 := &People{Name: "11"}
    // use constructor function
    s1 := structs.New(p1)
    m1, _ := s1.ToMap()

    fmt.Println(m1)

    // use static function
    m2, _ := structs.ToMap(p1)

    fmt.Println(m2)

    // Output:
    // map[name:11]
    // map[name:11]
}

Fields

Get all fields of a given struct, that the fields are abstract struct field

Signature:

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

Example:

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

Get an abstract field of a struct by given field name

Signature:

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

Example:

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

Check if the struct is valid

Signature:

func (s *Struct) IsStruct() bool

Example:

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
}