Update: I've found something similar in pkgsite https://github.com/golang/pkgsite/blob/beceacdece62d95d6dc41a9b5f09da7b2a021020/internal/database/reflect.go so I now assume it's not as far fetched as I thought until now.
Peter Müller schrieb am Freitag, 3. März 2023 um 16:53:07 UTC+1: > Hello, would you assess the following usage of `Var[T any]`, `v = > new(Var[T])` and `var person = rel.NewVar[Person]("person")` as valid > pattern, that also enables it to be used in further generic methods, or > would you rather prefer a codegen approach? > > ```go > type Var[T any] struct { > name string > attributeNames []string > typ reflect.Type > } > > func NewVar[T any](name string) (v *Var[T]) { > v = new(Var[T]) > v.name = name > > var typ *T > v.typ = reflect.TypeOf(typ).Elem() > v.attributeNames = make([]string, v.typ.NumField()) > for i := 0; i < v.typ.NumField(); i++ { > v.attributeNames[i] = v.typ.Field(i).Tag.Get("db") > } > > return v > } > ``` > > Example: > > > ```go > import "github.com/peter-mueller/rel" > > type Person struct { > Name string `db:"name"` > Age int `db:"age"` > } > > var personRel = rel.NewVar[Person]("person") > > func InsertGeneric[T any](v *rel.Var[T], value T) (stmt string, params > []any) { > stmt += fmt.Sprintf("INSERT INTO %s (%s)\n", v.Name(), > strings.Join(v.AttributeRef(), ", ")) > stmt += fmt.Sprintf("VALUES (%s)\n", strings.Join(v.Params("?"), ",")) > params = v.Tuple(value) > return stmt, params > } > > // compiler checks if a Person struct is inserted into the relvar > stmt, params := InsertGeneric(personRel, Person{"Ann", 21}) > res, err := db.ExecContext(ctx, stmt, params...) > ``` > > I think a non-generic alternative use would be to pass a empty struct > value, but then the compiler can't check the types on inserts : > > ```go > var personRel = rel.NewVar("person", Person{}) > Insert(personRel, Person{"Ann", 21}) > Insert(personRel, 12) > ``` > -- 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/6a06f87a-1139-4418-8cd0-d182df65ecd4n%40googlegroups.com.