github.com/dahs81/otto@v0.2.1-0.20160126165905-6400716cf085/foundation/factory.go (about)

     1  package foundation
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  )
     7  
     8  // Factory is a factory function for creating foundations.
     9  type Factory func() (Foundation, error)
    10  
    11  // StructFactory returns a factory function for creating a newly
    12  // instantiated copy of the type of v.
    13  func StructFactory(v Foundation) Factory {
    14  	t := reflect.TypeOf(v)
    15  	if t.Kind() == reflect.Ptr {
    16  		t = t.Elem()
    17  	}
    18  
    19  	return func() (Foundation, error) {
    20  		raw := reflect.New(t)
    21  		v, ok := raw.Interface().(Foundation)
    22  		if !ok {
    23  			return nil, fmt.Errorf(
    24  				"Failed to instantiate type: %#v", raw.Interface())
    25  		}
    26  
    27  		return v, nil
    28  	}
    29  }