本文整理汇总了Golang中reflect.NewValue函数的典型用法代码示例。如果您正苦于以下问题:Golang NewValue函数的具体用法?Golang NewValue怎么用?Golang NewValue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewValue函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: fillRuntimeIndexes
// fillRuntimeIndexes fills a runtimeIndexes structure will the field
// indexes gathered from the remoteTypes recorded in a runtimeValues
// structure.
func fillRuntimeIndexes(runtime *runtimeValues, out *runtimeIndexes) {
outv := reflect.Indirect(reflect.NewValue(out)).(*reflect.StructValue)
outt := outv.Type().(*reflect.StructType)
runtimev := reflect.Indirect(reflect.NewValue(runtime)).(*reflect.StructValue)
// out contains fields corresponding to each runtime type
for i := 0; i < outt.NumField(); i++ {
// Find the interpreter type for this runtime type
name := outt.Field(i).Name
et := runtimev.FieldByName(name).Interface().(*remoteType).Type.(*eval.StructType)
// Get the field indexes of the interpreter struct type
indexes := make(map[string]int, len(et.Elems))
for j, f := range et.Elems {
if f.Anonymous {
continue
}
name := f.Name
if name[0] >= 'a' && name[0] <= 'z' {
name = string(name[0]+'A'-'a') + name[1:]
}
indexes[name] = j
}
// Fill this field of out
outStructv := outv.Field(i).(*reflect.StructValue)
outStructt := outStructv.Type().(*reflect.StructType)
for j := 0; j < outStructt.NumField(); j++ {
f := outStructv.Field(j).(*reflect.IntValue)
name := outStructt.Field(j).Name
f.Set(indexes[name])
}
}
}
示例2: checkFuzzyEqual
func checkFuzzyEqual(a any, b any) (err os.Error) {
if !fuzzyEqual(a, b) {
err = os.NewError(fmt.Sprint(a, " != ", b,
":", reflect.NewValue(a), "!=", reflect.NewValue(b)))
}
return
}
示例3: parse1Param
// Parsuje parametr znajdujacy sie na poczatku frag. Pomija biale znaki przed
// parametrem i usuwa za nim (po wywolaniu frag[0] nie jest bialym znakiem).
func parse1Param(txt *string, lnum *int) (
par interface{}, err os.Error) {
frag := *txt
// Pomijamy biale znaki, ktore moga wystapic przed parametrem.
err = skipWhite(&frag, lnum)
if err != nil {
return
}
if frag[0] == '"' || frag[0] == '\'' {
// Parametrem jest tekst.
txt_sep := frag[0:1]
frag = frag[1:]
if len(frag) == 0 {
err = ParseErr{*lnum, PARSE_UNEXP_EOF}
return
}
// Parsujemy tekst parametru.
par, err = parse1(&frag, lnum, txt_sep)
if err != nil {
return
}
} else if uni.IsDigit(int(frag[0])) ||
str.IndexRune(seps_num, int(frag[0])) != -1 {
// Parametrem jest liczba
ii := findChar(frag, seps_nnum, lnum)
if ii == -1 {
err = ParseErr{*lnum, PARSE_UNEXP_EOF}
return
}
var iv int
iv, err = strconv.Atoi(frag[0:ii])
if err != nil {
var fv float
fv, err = strconv.Atof(frag[0:ii])
if err != nil {
err = ParseErr{*lnum, PARSE_BAD_FLOINT}
return
}
par = reflect.NewValue(fv)
} else {
par = reflect.NewValue(iv)
}
frag = frag[ii:]
} else {
par, err = parse1VarFun("", &frag, lnum, false)
if err != nil {
return
}
}
// Pomijamy biale znaki, ktore moga wystapic po parametrze.
err = skipWhite(&frag, lnum)
*txt = frag
return
}
示例4: routeHandler
func routeHandler(req *Request) *Response {
log.Stdout(req.RawURL)
path := req.URL.Path
ctx := Context{req, newResponse(200, "")}
for cr, route := range routes {
if !cr.MatchString(path) {
continue
}
match := cr.MatchStrings(path)
if len(match) > 0 {
if len(match[0]) != len(path) {
continue
}
if req.Method != route.method {
continue
}
ai := 0
handlerType := route.handler.Type().(*reflect.FuncType)
expectedIn := handlerType.NumIn()
args := make([]reflect.Value, expectedIn)
if expectedIn > 0 {
a0 := handlerType.In(0)
ptyp, ok := a0.(*reflect.PtrType)
if ok {
typ := ptyp.Elem()
if typ == contextType {
args[ai] = reflect.NewValue(&ctx)
ai += 1
expectedIn -= 1
}
}
}
actualIn := len(match) - 1
if expectedIn != actualIn {
log.Stderrf("Incorrect number of arguments for %s\n", path)
return newResponse(500, "")
}
for _, arg := range match[1:] {
args[ai] = reflect.NewValue(arg)
}
ret := route.handler.Call(args)[0].(*reflect.StringValue).Get()
var buf bytes.Buffer
buf.WriteString(ret)
resp := ctx.Response
resp.Body = &buf
return resp
}
}
return newResponse(404, "")
}
示例5: write
/**
* Write the command packet to the buffer and send to the server
*/
func (pkt *packetCommand) write(writer *bufio.Writer) (err os.Error) {
// Construct packet header
pkt.header = new(packetHeader)
pkt.header.length = 1
// Calculate packet length
var v reflect.Value
for i := 0; i < len(pkt.args); i++ {
v = reflect.NewValue(pkt.args[i])
switch v.Type().Name() {
default:
return os.ErrorString("Unsupported type")
case "string":
pkt.header.length += uint32(len(v.Interface().(string)))
case "uint8":
pkt.header.length += 1
case "uint16":
pkt.header.length += 2
case "uint32":
pkt.header.length += 4
case "uint64":
pkt.header.length += 8
}
}
pkt.header.sequence = 0
err = pkt.header.write(writer)
if err != nil {
return
}
// Write command
err = writer.WriteByte(byte(pkt.command))
if err != nil {
return
}
// Write params
for i := 0; i < len(pkt.args); i++ {
v = reflect.NewValue(pkt.args[i])
switch v.Type().Name() {
case "string":
_, err = writer.WriteString(v.Interface().(string))
case "uint8":
err = pkt.writeNumber(writer, uint64(v.Interface().(uint8)), 1)
case "uint16":
err = pkt.writeNumber(writer, uint64(v.Interface().(uint16)), 2)
case "uint32":
err = pkt.writeNumber(writer, uint64(v.Interface().(uint32)), 4)
case "uint64":
err = pkt.writeNumber(writer, uint64(v.Interface().(uint64)), 8)
}
if err != nil {
return
}
}
// Flush
err = writer.Flush()
return
}
示例6: run
// The function run manages sends and receives for a single client. For each
// (client Recv) request, this will launch a serveRecv goroutine to deliver
// the data for that channel, while (client Send) requests are handled as
// data arrives from the client.
func (client *expClient) run() {
hdr := new(header)
hdrValue := reflect.NewValue(hdr)
req := new(request)
reqValue := reflect.NewValue(req)
error := new(error)
for {
*hdr = header{}
if err := client.decode(hdrValue); err != nil {
expLog("error decoding client header:", err)
break
}
switch hdr.payloadType {
case payRequest:
*req = request{}
if err := client.decode(reqValue); err != nil {
expLog("error decoding client request:", err)
break
}
switch req.dir {
case Recv:
go client.serveRecv(*hdr, req.count)
case Send:
// Request to send is clear as a matter of protocol
// but not actually used by the implementation.
// The actual sends will have payload type payData.
// TODO: manage the count?
default:
error.error = "request: can't handle channel direction"
expLog(error.error, req.dir)
client.encode(hdr, payError, error)
}
case payData:
client.serveSend(*hdr)
case payClosed:
client.serveClosed(*hdr)
case payAck:
client.mu.Lock()
if client.ackNum != hdr.seqNum-1 {
// Since the sequence number is incremented and the message is sent
// in a single instance of locking client.mu, the messages are guaranteed
// to be sent in order. Therefore receipt of acknowledgement N means
// all messages <=N have been seen by the recipient. We check anyway.
expLog("sequence out of order:", client.ackNum, hdr.seqNum)
}
if client.ackNum < hdr.seqNum { // If there has been an error, don't back up the count.
client.ackNum = hdr.seqNum
}
client.mu.Unlock()
default:
log.Exit("netchan export: unknown payload type", hdr.payloadType)
}
}
client.exp.delClient(client)
}
示例7: TestUnpackArray
func TestUnpackArray(t *testing.T) {
b := bytes.NewBuffer([]byte{0x90, 0x91, 0x00, 0x92, 0x00, 0x01, 0x93, 0xd1, 0x00, 0x00, 0xd2, 0x00, 0x00, 0x00, 0x01, 0xd3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xdc, 0x00, 0x02, 0x00, 0x01, 0xdd, 0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x02, 0x03})
for _, v := range [](interface{}){[](interface{}){}, [](interface{}){int8(0)}, [](interface{}){int8(0), int8(1)}, [](interface{}){int16(0), int32(1), int64(2)}, [](interface{}){int8(0), int8(1)}, [](interface{}){int8(0), int8(1), int8(2), int8(3)}} {
retval, _, e := Unpack(b)
if e != nil {
t.Error("err != nil")
}
if !equal(reflect.NewValue(retval.Interface()), reflect.NewValue(v)) {
t.Errorf("%s != %s", retval.Interface(), v)
}
}
}
示例8: NewDemarshaler
func (j jsonMarshalingPolicy) NewDemarshaler(r io.Reader, p *proxyImpl) Demarshaler {
jm := &jsonDemarshaler{Decoder: json.NewDecoder(r), proxy: p}
var xb *bool = nil
jm.ptrBool = reflect.NewValue(xb).(*reflect.PtrValue)
var xi *int = nil
jm.ptrInt = reflect.NewValue(xi).(*reflect.PtrValue)
var xf *float64 = nil
jm.ptrFloat = reflect.NewValue(xf).(*reflect.PtrValue)
var xs *string = nil
jm.ptrString = reflect.NewValue(xs).(*reflect.PtrValue)
return jm
}
示例9: main
func main() {
flag.Usage = usage
flag.Parse()
if *showHelp {
usage()
return
}
if *showVersion {
fmt.Println("doozer", version)
return
}
if flag.NArg() < 1 {
fmt.Fprintf(os.Stderr, "%s: missing command\n", os.Args[0])
usage()
os.Exit(127)
}
cmd := flag.Arg(0)
c, ok := cmds[cmd]
if !ok {
fmt.Fprintln(os.Stderr, "Unknown command:", cmd)
usage()
os.Exit(127)
}
os.Args = flag.Args()
flag.Parse()
if *showHelp {
help(cmd)
return
}
args := flag.Args()
ft := reflect.Typeof(c.f).(*reflect.FuncType)
if len(args) != ft.NumIn() {
fmt.Fprintf(os.Stderr, "%s: wrong number of arguments\n", cmd)
help(cmd)
os.Exit(127)
}
vals := make([]reflect.Value, len(args))
for i, s := range args {
vals[i] = reflect.NewValue(s)
}
fv := reflect.NewValue(c.f).(*reflect.FuncValue)
fv.Call(vals)
}
示例10: send
func (s Send) send() {
// With reflect.ChanValue.Send, we must match the types exactly. So, if
// s.Channel is a chan interface{} we convert s.Value to an interface{}
// first.
c := reflect.NewValue(s.Channel).(*reflect.ChanValue)
var v reflect.Value
if iface, ok := c.Type().(*reflect.ChanType).Elem().(*reflect.InterfaceType); ok && iface.NumMethod() == 0 {
v = newEmptyInterface(s.Value)
} else {
v = reflect.NewValue(s.Value)
}
c.Send(v)
}
示例11: diff
func diff(t *testing.T, prefix string, have, want interface{}) {
hv := reflect.NewValue(have).(*reflect.PtrValue).Elem().(*reflect.StructValue)
wv := reflect.NewValue(want).(*reflect.PtrValue).Elem().(*reflect.StructValue)
if hv.Type() != wv.Type() {
t.Errorf("%s: type mismatch %v vs %v", prefix, hv.Type(), wv.Type())
}
for i := 0; i < hv.NumField(); i++ {
hf := hv.Field(i).Interface()
wf := wv.Field(i).Interface()
if !reflect.DeepEqual(hf, wf) {
t.Errorf("%s: %s = %v want %v", prefix, hv.Type().(*reflect.StructType).Field(i).Name, hf, wf)
}
}
}
示例12: Key
func (b *structBuilder) Key(k string) Builder {
if b == nil {
return nobuilder
}
switch v := reflect.Indirect(b.val).(type) {
case *reflect.StructValue:
t := v.Type().(*reflect.StructType)
// Case-insensitive field lookup.
k = strings.ToLower(k)
for i := 0; i < t.NumField(); i++ {
if strings.ToLower(t.Field(i).Name) == k {
return &structBuilder{val: v.Field(i)}
}
}
case *reflect.MapValue:
t := v.Type().(*reflect.MapType)
if t.Key() != reflect.Typeof(k) {
break
}
key := reflect.NewValue(k)
elem := v.Elem(key)
if elem == nil {
v.SetElem(key, reflect.MakeZero(t.Elem()))
elem = v.Elem(key)
}
return &structBuilder{val: elem, map_: v, key: key}
}
return nobuilder
}
示例13: Generate
func (*clientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value {
m := &clientHelloMsg{}
m.vers = uint16(rand.Intn(65536))
m.random = randomBytes(32, rand)
m.sessionId = randomBytes(rand.Intn(32), rand)
m.cipherSuites = make([]uint16, rand.Intn(63)+1)
for i := 0; i < len(m.cipherSuites); i++ {
m.cipherSuites[i] = uint16(rand.Int31())
}
m.compressionMethods = randomBytes(rand.Intn(63)+1, rand)
if rand.Intn(10) > 5 {
m.nextProtoNeg = true
}
if rand.Intn(10) > 5 {
m.serverName = randomString(rand.Intn(255), rand)
}
m.ocspStapling = rand.Intn(10) > 5
m.supportedPoints = randomBytes(rand.Intn(5)+1, rand)
m.supportedCurves = make([]uint16, rand.Intn(5)+1)
for i, _ := range m.supportedCurves {
m.supportedCurves[i] = uint16(rand.Intn(30000))
}
return reflect.NewValue(m)
}
示例14: AddHandler
func (self *Controller) AddHandler(regexp string, fun interface{}) {
self.callbacks.Push(&callback{
regexp,
reflect.NewValue(fun).(*reflect.FuncValue),
reflect.Typeof(fun).(*reflect.FuncType),
})
}
示例15: parseParams
/**
* Parse params given to Connect()
*/
func (mysql *MySQL) parseParams(p []interface{}) {
mysql.auth = new(MySQLAuth)
// Assign default values
mysql.auth.port = DefaultPort
mysql.auth.socket = DefaultSock
// Host / username are required
mysql.auth.host = p[0].(string)
mysql.auth.username = p[1].(string)
// 3rd param should be a password
if len(p) > 2 {
mysql.auth.password = p[2].(string)
}
// 4th param should be a database name
if len(p) > 3 {
mysql.auth.dbname = p[3].(string)
}
// Reflect 5th param to determine if it is port or socket
if len(p) > 4 {
v := reflect.NewValue(p[4])
if v.Type().Name() == "int" {
mysql.auth.port = v.Interface().(int)
} else if v.Type().Name() == "string" {
mysql.auth.socket = v.Interface().(string)
}
}
return
}