• Go reflect反射


    Go语言中的反射非常强大,可以对string, int, struct, func...进行反射,使用起来也比较简单。

    示例1:反射函数

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func Hello() {
        fmt.Println("hello world!")
    }
    
    func main() {
        valueOf := reflect.ValueOf(Hello)
        valueOf.Call(nil)
    }

    示例2:反射带参数的函数

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func Print(str ...string) {
        fmt.Println("str=", str)
    }
    func main() {
        valueOf := reflect.ValueOf(Print)
        i := make([]reflect.Value, 3)
        i[0] = reflect.ValueOf("1")
        i[1] = reflect.ValueOf("2")
        i[2] = reflect.ValueOf("3")
    
        valueOf.Call(i)
    }

    示例3: 结构体反射,实现Struct to Json的转换

    package main
    
    import (
        "reflect"
        "fmt"
    )
    
    type User struct {
        Name string `json:"name"`
        Age int
        Sex string
    }
    
    func TestType(a interface{}) {
        typeOf := reflect.TypeOf(a)
        fmt.Printf("typeof = %v
    ", typeOf)
        kind := typeOf.Kind()
        switch kind {
        case reflect.Int:
            fmt.Println("a is an int")
        case reflect.String:
            fmt.Println("a is a string")
        }
    }
    
    func TestValue(a interface{}) {
        valueOf := reflect.ValueOf(a)
        switch valueOf.Kind() {
        case reflect.Ptr:
            i := valueOf.Elem().Type()
            switch i.Kind() {
            case reflect.Int:
                valueOf.Elem().SetInt(10000)
            case reflect.String:
                valueOf.Elem().SetString("hello world")
            }
        }
    }
    
    func Marshal(a interface{}) {
        valueOf := reflect.ValueOf(a)
        typeOf := valueOf.Type()
        jsonStr := ""
        switch typeOf.Kind() {
        case reflect.Struct:
            numField := typeOf.NumField()
            for i:=0; i<numField; i++ {
                structField := typeOf.Field(i)
                valueField := valueOf.Field(i)
                name := structField.Name
                if structField.Tag.Get("json") != "" {
                    name = structField.Tag.Get("json")
                }
                if valueField.Type().Kind() == reflect.String {
                    jsonStr += fmt.Sprintf("  "%s": "%v"", name, valueField.Interface())
                } else {
                    jsonStr += fmt.Sprintf("  "%s": %v", name, valueField.Interface())
    
                }
                if numField - i > 1 {
                    jsonStr += ",
    "
                }
            }
            jsonStr = "{
    " + jsonStr + "
    }"
        }
        fmt.Printf("%s", jsonStr)
    }
    
    func main() {
        var a int
        TestType(a)
    
        var b string
        TestType(b)
    
        TestValue(&a)
        TestValue(&b)
    
        fmt.Println(a, b)
    
        var user User
        user.Name = "alex"
        user.Age = 100
        user.Sex = "man"
        Marshal(user)
    }

    参考文章:https://studygolang.com/articles/896

  • 相关阅读:
    awt
    登录校验 简单实现
    事务隔离级别
    事务的四大特性(ACID)
    多线程简单了解
    Eureka bug
    什么是存储过程
    filter和servlet的区别
    说说你对多线程锁机制的理解
    session的生命周期,session何时创建,何时销毁,session销毁的方式
  • 原文地址:https://www.cnblogs.com/vincenshen/p/9534794.html
Copyright © 2020-2023  润新知