• 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

  • 相关阅读:
    记录Integer比较问题
    代码中获取git输出
    python open mode
    elasticsearch Unrecognized VM option 'UseParNewGC'
    应用商店显示无法加载页面 请稍后重试
    deep learning with python前五章笔记
    QWeb2: Template 'systray_odoo_referral.gift_icon' not found
    wifi scapy
    struct.pack, struct.unpack详解
    python f-string
  • 原文地址:https://www.cnblogs.com/vincenshen/p/9534794.html
Copyright © 2020-2023  润新知