码迷,mamicode.com
首页 > 其他好文 > 详细

Go reflect反射

时间:2018-08-25 18:56:19      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:ring   hello   lse   sprint   ++   case   else   val   amp   

 

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\n", 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 += ",\n"
            }
        }
        jsonStr = "{\n" + jsonStr + "\n}"
    }
    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)
}

 

Go reflect反射

标签:ring   hello   lse   sprint   ++   case   else   val   amp   

原文地址:https://www.cnblogs.com/vincenshen/p/9534794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!