Go语言中使用反射的方法
“richiecqc”通过精心收集,向本站投稿了5篇Go语言中使用反射的方法,下面是小编整理后的Go语言中使用反射的方法,欢迎阅读分享,希望对大家有所帮助。
篇1: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语言程序设计有所帮助,
篇2:go语言使用RC4加密的方法
作者:令狐不聪 字体:[增加 减小] 类型:转载
这里需要使用rc4包来实现rc4加密,核心代码如下:
代码如下:
key := []byte{ 1, 2, 3, 4, 5, 6, 7 }
c, err := rc4.NewCipher(key)
dst := make([]byte, len(src))
c.XORKeyStream(dst, src)
希望本文所述对大家的Go语言程序设计有所帮助,
篇3:go语言中使用timer的常用方式
作者:heishui 字体:[增加 减小] 类型:
下面三段代码(A,b,C)的功能都是在5分钟后执行指定的函数的go语言代码:
代码如下:
// (A)
time.AfterFunc(5 * time.Minute, func {
fmt.Printf(“expired”)
}
// (B) create a Timer object
timer := time.NewTimer(5 * time.Minute)
<-timer.C
fmt.Printf(“expired”)
// (C) time.After() returns timer.C internally
<-time.After(5 * time.Minute)
fmt.Printf(“expired”)
希望本文所述对大家的Go语言程序设计有所帮助,
篇4:go语言使用scp的方法实例分析
作者:feiwen 字体:[增加 减小] 类型:转载
代码如下:
package main
import (
“code.google.com/p/go.crypto/ssh”
“crypto”
“crypto/rsa”
“crypto/x509”
“encoding/pem”
“fmt”
“io”
)
const privateKey = `content of id_rsa`
type keychain struct {
key *rsa.PrivateKey
}
func (k *keychain) Key(i int) (interface{}, error) {
if i != 0 {
return nil, nil
}
return &k.key.PublicKey, nil
}
func (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {
hashFunc := crypto.SHA1
h := hashFunc.New()
h.Write(data)
digest := h.Sum(nil)
return rsa.SignPKCS1v15(rand, k.key, hashFunc, digest)
}
func main() {
block, _ := pem.Decode([]byte(privateKey))
rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
clientKey := &keychain{rsakey}
clientConfig := &ssh.ClientConfig{
User: “wuhao”,
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(clientKey),
},
}
client, err := ssh.Dial(“tcp”, “127.0.0.1:22”, clientConfig)
if err != nil {
panic(“Failed to dial: ” + err.Error())
}
session, err := client.NewSession()
if err != nil {
panic(“Failed to create session: ” + err.Error())
}
defer session.Close()
go func() {
w, _ := session.StdinPipe()
defer w.Close()
content := “123456789\n”
fmt.Fprintln(w, “C0644”, len(content), “testfile”)
fmt.Fprint(w, content)
fmt.Fprint(w, “\x00”) // 传输以\x00结束
}()
if err := session.Run(“/usr/bin/scp -qrt ./”); err != nil {
panic(“Failed to run: ” + err.Error())
}
}
希望本文所述对大家的Go语言程序设计有所帮助,
篇5:go语言通过反射获取和设置结构体字段值的方法
作者:heishui 字体:[增加 减小] 类型:转载
这篇文章主要介绍了go语言通过反射获取和设置结构体字段值的方法,实例分析了Go语言反射的使用技巧,需要的朋友可以参考下
本文实例讲述了go语言通过反射获取和设置结构体字段值的方法,分享给大家供大家参考。具体实现方法如下:
代码如下:
type MyStruct struct {
N int
}
n := MyStruct{ 1 }
// get
immutable := reflect.ValueOf(n)
val := immutable.FieldByName(“N”).Int()
fmt.Printf(“N=%d\n”, val) // prints 1
// set
mutable := reflect.ValueOf(&n).Elem()
mutable.FieldByName(“N”).SetInt(7)
fmt.Printf(“N=%d\n”, n.N) // prints 7
希望本文所述对大家的go语言程序设计有所帮助,
【Go语言中使用反射的方法】相关文章:
9.用反射造句
10.go的短语






文档为doc格式