发布于 2016-01-24 01:18:20 | 132 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的GO语言教程,程序狗速度看过来!

Go语言

Go是一种新的语言,一种并发的、带垃圾回收的、快速编译的语言。Go是谷歌2009年发布的第二款编程语言。2009年7月份,谷歌曾发布了Simple语言,它是用来开发Android应用的一种BASIC语言。


这篇文章主要介绍了Go语言中使用反射的方法,实例分析了Go语言实现反射的技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了Go语言中使用反射的方法。分享给大家供大家参考。具体实现方法如下:

// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}

创建实例如下:

shabushabu = Dish.new
shabushabu.instance_variables # => []
shabushabu.name = "Shabu-Shabu"
shabushabu.instance_variables # => ["@name"]
shabushabu.origin = "Japan"
shabushabu.instance_variables # => ["@name", "@origin"]

完整代码如下:

package main
import(
  "fmt"
  "reflect"
)
 
func main(){
  // iterate through the attributes of a Data Model instance
  for name, mtype := range attributes(&Dish{}) {
    fmt.Printf("Name: %s, Type %s\n", name, mtype.Name())
  }
}
 
// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}
 
// Example of how to use Go's reflection
// Print the attributes of a Data Model
func attributes(m interface{}) (map[string]reflect.Type) {
  typ := reflect.TypeOf(m)
  // if a pointer to a struct is passed, get the type of the dereferenced object
  if typ.Kind() == reflect.Ptr{
    typ = typ.Elem()
  }
 
  // create an attribute data structure as a map of types keyed by a string.
  attrs := make(map[string]reflect.Type)
  // Only structs are supported so return an empty result if the passed object
  // isn't a struct
  if typ.Kind() != reflect.Struct {
    fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
    return attrs
  }
 
  // loop through the struct's fields and set the map
  for i := 0; i < typ.NumField(); i++ {
    p := typ.Field(i)
      if !p.Anonymous {
        attrs[p.Name] = p.Type
      }
     }
  return attrs
}

希望本文所述对大家的Go语言程序设计有所帮助。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务