Go语言中文网 为您找到相关结果 36

golang中struct关于反射tag

package main import ( "fmt" "reflect" ) type User struct { name string `json:name-field` age int } func main() { user := &User{"John Doe The Fourth", 20} field, ok := reflect.TypeOf(user).Elem().FieldByName("name") if !ok { panic("Field not found") } fmt.Println(getStructTag(field)) } func getStructTag(f reflect.StructField) string { return string(...阅读全文

博文 2015-06-17 20:03:06 paladinosment

go 速学 - 14 - 反射

目录 反射 reflection 使用反射 前提 定义一个结构及方法 反射所有字段及方法 访问结构中的匿名字段 动态修改属性的值 动态调用方法 摘要 使用反射,匿名字段,动态修改属性,动态调用方法 反射 reflection 使用反射 前提 使用反射之前必须引用包 reflect 定义一个结构及方法 import "reflect" type User struct { Id int Name string Age int } func (u User) say() { fmt.Println("hello") } u := User{Id: 1, Name: "Peter", Age: 20} 反射所有字段及方法 reflect.TypeOf(o) 用于获得类型原型 reflect.Val...阅读全文

博文 2015-05-01 23:00:00 mrseasons

golang的反射机制

go反射 什么是反射?使用反射可以实现什么功能? 反射提供了一种可以操作任意类型数据结构的能力。通过反射你可以实现对任意类型的深度复制,可以对任意类型执行自定义的操作。另外由于golang可以给结构体定义tag熟悉,结合反射,于是就可以实现结构体与数据库表、结构体与json对象之间的相互转换。 使用反射需要注意什么事情? 使用反射时需要先确定要操作的值是否是期望的类型,是否是可以进行“赋值”操作的,否则reflect包将会毫不留情的产生一个panic。 struct initializer示例 go-struct-initializer 是我在学习golang反射过程中实现的一个可以根据struct tag初始化结构体的go library,这里对其中用到的反射技术做一下说明 package...阅读全文

博文 2016-10-04 05:00:03 ylwh8679

golang通过反射动态调用方法

func Call(m map[string]interface{}, name string, params ...interface{}) ([]reflect.Value, error) { f := reflect.ValueOf(m[name]) if len(params) != f.Type().NumIn() { return nil, errors.New("the number of input params not match!") } in := make([]reflect.Value, len(params)) for k, v := range params { in[k] = reflect.ValueOf(v) } return f.Call(in), ni...阅读全文

博文 2017-09-19 12:30:01 xiazh

golang 反射结构字段类型

golang 反射用法,做个笔记. package main import ( "fmt" "reflect" ) type roles struct { roleId int roleName string } type User struct { Name string Age int Email string NickName string Telphone int Roles roles } func main() { u := User{Name: "Name", Age: 30, Email: "xxxx@afanty3d.com", NickName: "omni360", Telphone: xxxxx, Roles: roles{roleId: 1001, roleName...阅读全文

博文 2015-11-02 15:00:31 omni360

golang走起(三)list简单使用和interface{}

golang走起(三)list简单使用和interface{} 代码如下: package main import ( "container/list" "fmt" ) type Person struct { age int } func main() { l := list.New() for i := 0; i < 5; i++ { p := Person{age: i * 10} l.PushBack(p) } for i := 5; i < 10; i++ { l.PushBack(i) } i := 0 // 遍历 for v := l.Front(); v != nil; v = v.Next() { if i > 4 { c := v.Value.(int) fmt.Prin...阅读全文

博文 2016-04-18 18:00:05 zjp114695092

<2> go -反射-函数map化

代码编程中,用方法调用匹配名字的函数,非常有效 利用go的反射机制可以实现 import ( "errors" "fmt" "reflect" ) func foor() { fmt.Println("Start->foor()") } func say(number int) { fmt.Printf("This text is %d", number) } func Call(m map[string]interface{}, name string, params ...interface{}) (result []reflect.Value, err error) { f := reflect.ValueOf(m[name]) if len(params) != f.Type().N...阅读全文

博文 2015-12-22 13:00:00 a11101171

golang 反射

package main import ( "fmt" "reflect" ) type Person struct{} func (p *Person) Run() { fmt.Println("person running") } func doit(object interface{}, method interface{}) { v := reflect.ValueOf(object) f := reflect.ValueOf(method) f.Call([]reflect.Value{v}) } func main() { p := new(Person) doit(p, (*Person).Run) ...阅读全文

博文 2014-10-04 19:26:58 Mocos

go深度拷贝reflect版

2.通过反射的方式拷贝结构 package main import ( "fmt" "reflect" "time" ) type ( Player struct { Id int Level int Heroes map[int]*Hero Equips []*Equip } Hero struct { Id int Level int Skills []*Skill } Equip struct { Id int Level int } Skill struct { Id int Level int } ) func NewHero() *Hero { return &Hero{ Id: 1, Level: 1, Skills: append([]*Skill{NewSkill()}, ...阅读全文

博文 2018-07-21 00:30:02 LittleLee

go语言中的反射的使用

今天尝试了一下使用go语言中的反射来将struct类型转换成xml,结果相当纠结。首先去看了一下go的reflect包的实现,根据go的规则,首先应该去看一个NewXXX的方法,结果发现了一个叫NewValue的方法,通过这个方法我们能够得到一个Value接口。另外我们还应该注意到,go的反映实现中将Type和Value分开了,于是还有另外一个接口Type. type Value interface { // Type returns the value's type. Type() Type // Interface returns the value as an interface{}. Interface() interface{} // CanSet returns whether ...阅读全文

博文 2014-10-04 19:25:58 HopingWhite

The Laws of Reflection(Go语言反射定律)

载自 The Go Blog The Laws of Reflection 6 September 2011 Introduction Reflection in computing is the ability of a program to examine its own structure, particularly through types; it's a form of metaprogramming. It's also a great source of confusion. In this article we attempt to clarify things by explaining how reflection works in Go. Each language'...阅读全文

博文 2016-01-28 03:00:02 basque

go语言结构体反射的使用

reflect.Value区分CanSet和Can not Set的, 所以, 必须要返回成Can set的reflect.Value如: s := reflect.ValueOf(&t).Elem() 然后就可以happy的设值了, 可是不能随便设值的, 一个通用的方法就是使用Set(v Value)方法, 所以之前必须将值转成reflect.Value类型, 下面的这段代码就是转成Value类型 sliceValue := reflect.ValueOf([]int{1, 2, 3}) // 这里将slice转成reflect.Value类型 完整参考: type T struct { Age int Name string Children []int } t := T{12, "so...阅读全文

博文 2015-11-14 18:00:00 haitgo

GO语言练习:反射

列举几个反射的例子:1)简单类型反射,2)复杂类型反射,3)对反射回来的数据的可修改属性 1、简单类型反射 1.1)代码 package main import ( "fmt" "reflect" ) func main() { var x float64 = 3.4 v := reflect.ValueOf(x) fmt.Println("type :", v.Type()) fmt.Println("kind is float64:", v.Kind() == reflect.Float64) fmt.Println("value:", v.Float()) } 1.2)运行结果 $ go run reflect.go type : float64 kind is float64: tr...阅读全文

博文 2015-08-01 03:00:01 fengbohello

go reflect 3 rules

1. Reflection goes from interface value to reflection Object. 反射可以从接口值得到反射对象 使用到reflect methods: reflect.ValueOf(i interface{}) Value reflect.TypeOf(i interface{}) Type 2. Reflection goes from refelction object to interface value. 反射可以从反射对象获得接口值 使用到reflect methods: reflect.New(typ Type) Value reflect.Zero(typ Type) Value func (v Value) Type() Type ...阅读全文

博文 2015-11-10 22:00:00 hittata

Golang reflect 反射 struct 动态获取time.Time类型的值

直接上代码 package main import ( "fmt" "reflect" "testing" "time" ) type Stu struct { Str string Time time.Time } func TestTime(t *testing.T) { stu := Stu{Str: "test", Time: time.Now()} print(stu) } func print(t interface{}) { getType := reflect.TypeOf(t) getValue := reflect.ValueOf(t) for i := 0; i < getType.NumField(); i++ { field := getType.Field(i) ...阅读全文

博文 2020-02-25 22:32:52 承诺一时的华丽

Golang的反射reflect深入理解和示例

本人认为讲解的最好的文章,在此做个备案。方便以后查询。 微信链接地址: https://mp.weixin.qq.com/s?__biz=MzI2NzE3NzMzNQ==&mid=2650555706&idx=1&sn=c5383ac15c0038fdf2ff29152ee419b5&chksm=f28a3922c5fdb034831e93fd82d760111fd07dc1b0ee6748f55fa0be6f569d46875b6631b097&mpshare=1&scene=1&srcid=&sharer_sharetime=1576809179753&sharer_shareid=9a8fb33c226ef040ec830cafc7905e51&key=e149ed35f0e9d79c...阅读全文

博文 2019-12-21 06:32:44 caoxinyiyi

反射struct中的struct得到

下面代码希望自定义一个template函数,函数返回值TF,结果却得到了错误,求解。 ``` package main import ( "fmt" "os" "reflect" "text/template" ) func getByKey(data interface{}, keys ...string) interface{} { var rdata reflect.Value for _, k := range keys { rdata = reflect.ValueOf(data) switch rdata.Kind() { case reflect.Map: md...阅读全文

golang-反射机制

1,写数据库dao层的时候用到了反射机制。在反射的时候要注意你的对象时指针还是结构体这样区别也很大。以下接受几种常用的放射方法 reflect.type of package main import ( "fmt" "reflect" ) type hehe struct { NameFile string "PrimaryKey" age int } func main() { hehe := &hehe{"ssssssssssss", 33} yingShe(hehe) } func yingShe(obj interface{}) { hehe := &hehe{"ssssssssssss", 22} for i := 0; i < reflect.TypeOf(obj).Elem()...阅读全文

博文 2016-04-10 20:00:01 shuanger_

Golang 一些小例——反射

package main import ( "fmt" "reflect" ) type A struct { B Name string Age int UseTool bool } type B struct { C Name1 string Age1 int UseTool1 bool } type C struct { Name2 string Age2 int UseTool2 bool } func main() { m := B{C{"aa", 12, true}, "aa", 12, true} u := A{m, "aa", 12, true} getInfo(u) getStructInfo(u) }func getInfo(obj interface{}) { objC...阅读全文

博文 2015-06-17 20:02:32 LanX_Fly

go 反射

// reflect.go package main import ( "fmt" "reflect" ) type Bird struct { Name string LifeExpectance int } func (b *Bird) Fly() { fmt.Println("I am flying...") } func main() { sparrow := &Bird{"SParrow", 3} s := reflect.ValueOf(sparrow).Elem() typeOfT := s.Type() for i := 0; i < s.NumField(); i++ { f := s.Field(i) fmt.Printf("%d: %s %s = %v\n", i, t...阅读全文

博文 2017-05-03 16:00:24 痞子汤

Golang 反射 reflect 得 Bug

package mainimport ( "fmt" "reflect")type GoRute struct {}func (gr *GoRute) Test(a, b string) (string, error) { return a + " " + b, nil}func (gr *GoRute) Demo(a, b string) (string, error) { return a + " DDM " + b, nil}func main() { RuteRun("GoRute", "Test") RuteRun("GoRute", "Demo")}func RuteRun(ctl, mtd string) { switch ctl { case "GoRute": gr := ...阅读全文

博文 2018-11-29 17:06:43 yujianxianjun

GO 反射(reflection)

// jsondemo project main.go package main import ( "fmt" "reflect" ) type T struct { A int B string } func main() { //1 var x float64 = 3.4 fmt.Println("type:", reflect.TypeOf(x)) v := reflect.ValueOf(x) //reflect.Value fmt.Println("type", v.Type()) fmt.Println("kind is float64:", v.Kind() == reflect.Float64) fmt.Println("value:", v.Float()) //2 p :...阅读全文

博文 2017-05-11 09:00:44 痞子汤

go语言反射reflect

//UnKonwnJSONUnmarshal json func UnKonwnJSONUnmarshal(data []byte, key string) (vv interface{}) { var f interface{} if err := json.Unmarshal(data, &f); err == nil { m := f.(map[string]interface{}) for k, v := range m { if key == k { switch vv := v.(type) { case string: fmt.Println(k, "is string", vv) return vv case int: fmt.Println(k, "is int", vv)...阅读全文

博文 2016-09-10 18:00:02 guoer9973

Golang 反射

开发十年,就只剩下这套Java开发体系了 >>> todo (adsbygoogle = window.adsbygoogle || []).push({}); function googleAdJSAtOnload() { var element = document.createElement("script"); element.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"; element.async = true; document.body.appendChild(element); } if (window.addEventListener) { window.addEventListener(...阅读全文

博文 2018-09-23 01:33:06 FalconChen

understand reflection by example 通过代码了解反射

通过代码学习 reflection, 直接上代码 代码如下: ```go package main import ( "fmt" "reflect" ) type Student struct { name string age int `` } func (s *Student) Study() { fmt.Print("Studying reflection...") } func (s Student) Learn() { fmt.Print("Learning reflection...") } type MyStudent Student func main() { var obj interface{} //int obj = 1 ShowObjInfo(obj) //*int ...阅读全文

博文 2019-10-05 00:58:48 guoapeng