reflectx

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2020 License: MIT Imports: 2 Imported by: 34

Documentation

Overview

反射相关的代码

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BytesToString

func BytesToString(b []byte) (s string)

BytesToString []byte to string without data copy

func StringToBytes

func StringToBytes(s string) (b []byte)

StringToBytes string to []byte without data copy

func StructToMap

func StructToMap(data interface{}, depth int, tag ...string) map[string]interface{}

StructToMap 将结构体转为map类型, 参数: data为结构体地址变量, depth为转换的深度,0表示不递归转换struct, <0表示无限递归转换,>0表示递归转换的深度, tag为可选,不指定则全部字段输出,否则将指定tag的字段输出到map

Example
package main

import (
	"fmt"

	"github.com/recallsong/go-utils/reflectx"
)

func main() {
	type Inner struct {
		Age       int `api:"age"`
		NotOutput int
	}
	type Detail struct {
		Address   string `api:"address"`
		Inner     Inner  `api:"inner"`
		NotOutput int
	}
	type Person struct {
		Name      string  `api:"name"`
		Detail    Detail  `api:"detail"`
		DetailPtr *Detail `api:"detail_ptr"`
		Inner     Inner   `api:"inner"`
		NotOutput int     `api:"-"`
	}
	detail := Detail{Address: "xxx@xxx.com", Inner: Inner{Age: 18}, NotOutput: 100}
	s := Person{Name: "Song", Detail: detail, DetailPtr: &detail, Inner: Inner{Age: 20}}
	// 把Person转换成map
	m := reflectx.StructToMap(s, 0, "api")
	fmt.Println(m["detail"])
	fmt.Println(m["detail_ptr"])
	fmt.Println(m["inner"])
	// 把Person转换成map,递归1层,把Detail、DetailPtr、Inner也转换成map
	m = reflectx.StructToMap(s, 1, "api")
	fmt.Println(m["inner"])
}
Output:

{xxx@xxx.com {18 0} 100}
&{xxx@xxx.com {18 0} 100}
{20 0}
map[age:20]

Types

type ReadonlyBytes

type ReadonlyBytes []byte

ReadonlyBytes is readonly []byte

func (ReadonlyBytes) String

func (b ReadonlyBytes) String() (s string)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL