Demo entry 6633955

go

   

Submitted by anonymous on Aug 07, 2017 at 11:27
Language: Go. Code size: 811 Bytes.

package main

import (
    "fmt"
    "reflect"
)

var typeRegistry = make(map[string]reflect.Type)

func registerType(elem interface{}) {
    t := reflect.TypeOf(elem).Elem()
    typeRegistry[t.Name()] = t
}

func newStruct(name string) (interface{}, bool) {
    elem, ok := typeRegistry[name]
    if !ok {
        return nil, false
    }
    return reflect.New(elem).Elem().Interface(), true
}

func init() {
    registerType((*test)(nil))
}

type test struct {
    Name string
    Sex  int
}

func main() {
    structName := "test"

    s, ok := newStruct(structName)
    if !ok {
        return
    }

    fmt.Println(s, reflect.TypeOf(s))

    t, ok := s.(test)
    if !ok {
        return
    }
    t.Name = "i am test"
    fmt.Println(t, reflect.TypeOf(t))
}

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).