Skip to content

xiaoxin01/typeregistry

master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 

a library to create type dynamically

Report Build Status

how to use

// 1. define struct
type Student struct {
	Age  int
	Name string
}

// 2. add reflect type
key := AddType(new(Student))

// 3. create struct from registed key
student := Make(key)

custom registed key

var i interface{} = new(Student)

// use lowercase struct name as key
name := AddTypeWithKey(i, func(i interface{}) string {
	tpe := reflect.TypeOf(i).Elem()
	return strings.ToLower(tpe.Name())
})

student, ok := Create("student").(*Student)

benchmark

go.exe test -benchmem -run=^$ supperxin/typeregistry -bench ^BenchmarkMake$

goos: windows
goarch: amd64
pkg: supperxin/typeregistry
BenchmarkMake-8   	 8823256	       138 ns/op	      64 B/op	       2 allocs/op
PASS
ok  	supperxin/typeregistry	1.551s
go.exe test -benchmem -run=^$ supperxin/typeregistry -bench ^BenchmarkCreateDirectly$

goos: windows
goarch: amd64
pkg: supperxin/typeregistry
BenchmarkCreateDirectly-8   	1000000000	         0.593 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	supperxin/typeregistry	0.857s

About

create type dynamically in Golang

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages