I have developed a library that depends very much on reflect package. It 
caches a specific type and return a function that encodes(does something 
with) with that kind /type of data. Think of defining database schema using 
types and generating functions to validate/update/insert data.

I reduced it to a basic example below. Can the generics feature from Go 
help me make it any safer?  Ideally I would like to make the program below* 
not to compile *due the errors of invalid params passed to *PrintT* instead 
 to  throw dynamically at runtime.
package main

import (
"errors"
"fmt"
"reflect"
)

type T struct {
F1 string
F2 int
}

type T2 struct {
F1 float32
F2 bool
}

var PrintT = Function(T{})

func main() {

if err := PrintT("one", 1); err != nil {
fmt.Printf("err %v", err)
}
if err := PrintT("one", 1, "another"); err != nil {
fmt.Printf("err %v", err)
}
if err := PrintT("one", "one"); err != nil {
fmt.Printf("err %v", err)
}

}

type ReturnFunc func(params ...interface{}) error

func Function(v interface{}) ReturnFunc {

var paramTypes []reflect.Type
tv := reflect.TypeOf(v)
for i := 0; i < tv.NumField(); i++ {
paramTypes = append(paramTypes, tv.Field(i).Type)
}
fn := func(param ...interface{}) error {
// validate input
if len(param) != len(paramTypes) {
return errors.New("invalid number of params passed")
}
for k, v := range param {
if reflect.TypeOf(v) != paramTypes[k] {
return errors.New("invalid type passed")
}
}
// do something with the params
fmt.Println(param...)
return nil
}
return fn
}


https://go2goplay.golang.org/p/1MJynmFhq6B

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/2bc1a657-c4e0-42a1-82b0-8bc605c429a2n%40googlegroups.com.

Reply via email to