Quantcast
Channel: User Norbert - Stack Overflow
Viewing all articles
Browse latest Browse all 42

Answer by Norbert for Best patterns for dynamic checks in Go without reflection?

$
0
0

3 directions, not the most straight forward, but they can reduce your check blocks:

Method 1: Define your own annotation

Golang has annotations in structs

type bla struct {  t string `json:"some,omitempty"`}

This is actually an open annotation structure (tags).

A nice example (contains some reflection) is https://github.com/mitchellh/mapstructure

Look at line 374 of the mapstructure.go file. It is pretty re-usable, and you could use it as base for your own annotation.

To use it in your context you would create types which you can then parse.

Method 2: DRY check function

Your check seems to be the same or similar.

A generic comparator which iterates over fields:

func check(fields ...interface{}) error {  for v:=range fields {    if v==nil {      return errors.New("nil")    }    switch v.(type) {      case *string:        if len([]rune(*v)) > MAX_ALLOWED_LEN) {          return errors.New("exceeded max allowable length")        }      }      ...    }}

Method 3: Generics.

The switch type in method 2 might be able to be rewritten in a generic style. Not easier, but can be prettier.


Viewing all articles
Browse latest Browse all 42

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>