gitee.com/h79/goutils@v1.22.10/common/option/option.go (about)

     1  package option
     2  
     3  type Option interface {
     4  	String() string
     5  	Type() int
     6  	Value() any
     7  }
     8  
     9  type Opt[T any] struct {
    10  	v T
    11  	d string
    12  	t int
    13  }
    14  
    15  func WithOpt[T any](v T, desc string, t int) Option {
    16  	return &Opt[T]{v: v, d: desc, t: t}
    17  }
    18  
    19  func (o Opt[T]) String() string {
    20  	return o.d
    21  }
    22  func (o Opt[T]) Type() int  { return o.t }
    23  func (o Opt[T]) Value() any { return o.v }
    24  
    25  func Filter(filter func(opt Option) bool, opts ...Option) {
    26  	if len(opts) == 0 {
    27  		return
    28  	}
    29  	for i := range opts {
    30  		if opts[i] != nil && filter(opts[i]) {
    31  			return
    32  		}
    33  	}
    34  }
    35  
    36  func Exist(ty int, opts ...Option) (Option, bool) {
    37  	if len(opts) == 0 {
    38  		return nil, false
    39  	}
    40  	for i := range opts {
    41  		if opts[i] != nil && opts[i].Type() == ty {
    42  			return opts[i], true
    43  		}
    44  	}
    45  	return nil, false
    46  }
    47  
    48  func Select[T any](t int, defValue T, opts ...Option) T {
    49  	if len(opts) == 0 {
    50  		return defValue
    51  	}
    52  	r, ok := Exist(t, opts...)
    53  	if !ok {
    54  		return defValue
    55  	}
    56  	if ret, o := r.Value().(T); o {
    57  		return ret
    58  	}
    59  	return defValue
    60  }
    61  
    62  func SelectV2[T any](t int, defValue T, opts ...Option) (T, bool) {
    63  	if len(opts) == 0 {
    64  		return defValue, false
    65  	}
    66  	r, ok := Exist(t, opts...)
    67  	if !ok {
    68  		return defValue, false
    69  	}
    70  	if ret, o := r.Value().(T); o {
    71  		return ret, true
    72  	}
    73  	return defValue, false
    74  }