github.com/vugu/vugu@v0.3.6-0.20240430171613-3f6f402e014b/vgform/values.go (about)

     1  package vgform
     2  
     3  import "errors"
     4  
     5  // StringValuer is a string that can be gotten and set.
     6  type StringValuer interface {
     7  	StringValue() string
     8  	SetStringValue(string)
     9  }
    10  
    11  // TODO: hm, would this not be better as:
    12  // type StringValue string
    13  // func (s *StringValue) StringValue() string {
    14  // This would allow people to either cast a *string to *StringValue
    15  // or just use vgform.StringValue directly as a struct member and
    16  // pass it's address right into the Value property, i.e.
    17  // < ... :Value="&c.SomeStringValue">
    18  // Maybe a StrPtr(&c.RegularString) would be good.
    19  
    20  // NOTE: It is useful to do `StringPtr{something}` so give careful
    21  // thought before adding another field to StringPtr.
    22  // StringPtr must be a struct because you cannot add methods to
    23  // types declared as `type x *string`.
    24  
    25  // StringPtr implements StringValuer on a string pointer.
    26  type StringPtr struct {
    27  	Value *string
    28  }
    29  
    30  // StringPtrDefault returns a StringPtr and sets the underlying string to def if it empty.
    31  func StringPtrDefault(p *string, def string) StringPtr {
    32  	if p == nil {
    33  		panic(errors.New("StringPtr must not have a nil pointer"))
    34  	}
    35  	if *p == "" {
    36  		*p = def
    37  	}
    38  	return StringPtr{p}
    39  }
    40  
    41  // StringValue implements StringValuer
    42  func (s StringPtr) StringValue() string {
    43  	// I can't see any benefit to hiding the nil ptr by returning "",
    44  	// especially because when the value comes back with SetStringValue
    45  	// we would be forced to throw it away.
    46  	// Since this is probably a mistake we panic and let someone know.
    47  	if s.Value == nil {
    48  		panic(errors.New("StringPtr must not have a nil pointer"))
    49  	}
    50  	return *s.Value
    51  }
    52  
    53  // SetStringValue implements StringValuer
    54  func (s StringPtr) SetStringValue(v string) {
    55  	if s.Value == nil {
    56  		panic(errors.New("StringPtr must not have a nil pointer"))
    57  	}
    58  	*s.Value = v
    59  }