go反射

go反射

内置pair

image

每个值都有pair

var a string
//pair<statictype:string,value:"aceld">
a = "aceld"
//pair<type:string, value:"aceld">
var allType interface{}
allType = a

pair代码示例

type Reader interface {
   ReadBook()
}
type Writer interface {
   WriteBook()
}

//具体类型
type Book struct {
}

func (this *Book) ReadBook() {
   fmt.Println("Read a Book")
}
func (this *Book) WriteBook() {
   fmt.Println("Write a Book")
}

func main() {
   //b: pair<type: Book, value: book{}地址>
   b := &Book{}
   //r: pair<type:, value:>
   var r Reader
   //r: pair<type: Book, value: book{}地址>
   r = b
   r.ReadBook()
   var W Writer
   //r: pair<type:Book, value: book{ }地址>
   W = r.(Writer) //此处的断言为什么会成功? 因为W r具体的type是- -致
   W.WriteBook()
}

反射

package main

import (
	"fmt"
	"reflect"
)

type User struct {
	Id   int
	Name string
	Age  int
}


func (this *User) Call() {
	fmt.Println("user is called ..")
	fmt.Printf("%v\n", this)
}


func (this User) Xall() {
	fmt.Println("user is called ..") // 非指针的才可以导出获取到  大坑
	fmt.Printf("%v\n", this)
}

func main() {
	user := User{1, "Aceld", 18}
	DoFiledAndMethod(user)
}
func DoFiledAndMethod(input interface{}) {
	//获取input的type
	inputType := reflect.TypeOf(input)
	fmt.Println("inputType is :", inputType.Name())
	//获取input的value
	inputValue := reflect.ValueOf(input)
	fmt.Println("inputValue is:", inputValue)
	//通过type获取里面的字段
	//1.获取interface的reflect . Type,通过Type得到NumField , 进行遍历
	//2.得到每个field,数据类型
	//3.通过filed有一个Interface()方法等到对应的value
	for i := 0; i < inputType.NumField(); i++ {
		field := inputType.Field(i)
		value := inputValue.Field(i).Interface()
		fmt.Printf("%s: %v = %v\n", field.Name, field.Type, value)
	}
	//通过type获取里面的方法,调用
	for i := 0; i < inputType.NumMethod(); i++ {
		m := inputType.Method(i)
		fmt.Printf("%s: %v\n", m.Name, m.Type)

	}
}

go反射解析结构体标签Tag

package main

import (
   "fmt"
   "reflect"
)
// 结构体标签的定义
type resume struct {
   Name string `info:"name" doc:"我的名字"`
   Sex  string `info:"sex"`
}

func findTag(str interface{}) {
   t := reflect.TypeOf(str).Elem()
   for i := 0; i < t.NumField(); i++ {
      taginfo := t.Field(i).Tag.Get("info")
      tagdoc := t.Field(i).Tag.Get("doc")
      fmt.Println("info: ",taginfo, " doc: ", tagdoc)
   }
}
func main() {
   var re resume
   findTag(&re)
}

结构体标签在json中的应用

package main

import (
   "encoding/json"
   "fmt"
)

type Movie struct {
   Title  string   `json: "title"`
   Year   int      `json: "year"`
   Price  int      `json:    " rmb""`
   Actors []string `json: "actors"`
}

func main() {
   movie := Movie{"喜剧之王", 2000, 10, []string{"xingye", "zhangbozhi"}}
   //编码的过程结构体 --> json
   jsonStr, err := json.Marshal(movie)
   if err != nil {
      fmt.Println("json marshal error", err)
      return
   }
   fmt.Printf("jsonStr = %s\n", jsonStr)
   	//解码的过程jsonstr -- -- >结构体
	//jsonStr = {"title":"重园之王" ,"year" ;20B8," rib?" ;10, "actors"; ["xiugye" ,"shangbazhi"]}
	myMovie := Movie{}
	err = json.Unmarshal(jsonStr, myMovie)
	if err != nil {
		fmt.Println("json unmarshal error'", err)
		return
	}
}
posted @ 2021-10-06 11:37  野兽Gentleman  阅读(80)  评论(0编辑  收藏  举报