github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/fields/03_compose/fields.go (about)

     1  package main
     2  
     3  import "fmt"
     4  
     5  // using composed types
     6  //gistsnip:start:field
     7  type Field interface {
     8  	Name() string
     9  	Assign(typ string, value interface{}) error
    10  }
    11  
    12  type Float struct {
    13  	FieldName string
    14  	Value     *float64
    15  }
    16  
    17  func (s Float) Name() string { return s.FieldName }
    18  func (s Float) Assign(typ string, val interface{}) error {
    19  	uv, ok := val.(float64)
    20  	if !ok || typ != "float" {
    21  		return fmt.Errorf("expected float, got %T and %v", val, typ)
    22  	}
    23  	*s.Value = uv
    24  	return nil
    25  }
    26  
    27  //gistsnip:end:field
    28  
    29  type Uint struct {
    30  	FieldName string
    31  	Value     *uint
    32  }
    33  
    34  func (s Uint) Name() string { return s.FieldName }
    35  func (s Uint) Assign(typ string, val interface{}) error {
    36  	uv, ok := val.(float64)
    37  	if !ok || typ != "uint" {
    38  		return fmt.Errorf("expected uint, got %T and %v", val, typ)
    39  	}
    40  	*s.Value = uint(uv)
    41  	return nil
    42  }