@@ -43,23 +43,26 @@ func StrToBool(s string) (bool, error) {
4343}
4444
4545// FormatWithArgs format message with args
46+ //
47+ // - only one element, format to string
48+ // - first is format: fmt.Sprintf(firstElem, fmtAndArgs[1:]...)
49+ // - all is args: return fmt.Sprint(fmtAndArgs...)
4650func FormatWithArgs (fmtAndArgs []any ) string {
4751 ln := len (fmtAndArgs )
4852 if ln == 0 {
4953 return ""
5054 }
5155
5256 first := fmtAndArgs [0 ]
53-
5457 if ln == 1 {
55- if msgAsStr , ok := first .(string ); ok {
56- return msgAsStr
58+ if str , ok := first .(string ); ok {
59+ return str
5760 }
5861 return fmt .Sprintf ("%+v" , first )
5962 }
6063
6164 // is template string.
62- if tplStr , ok := first .(string ); ok {
65+ if tplStr , ok := first .(string ); ok && strings . IndexByte ( tplStr , '%' ) >= 0 {
6366 return fmt .Sprintf (tplStr , fmtAndArgs [1 :]... )
6467 }
6568 return fmt .Sprint (fmtAndArgs ... )
@@ -86,11 +89,6 @@ var StrBySprintFn = func(v any) (string, error) {
8689 return fmt .Sprint (v ), nil
8790}
8891
89- // WithHandlePtr set ConvOption.HandlePtr option
90- func WithHandlePtr (opt * ConvOption ) {
91- opt .HandlePtr = true
92- }
93-
9492// WithUserConvFn set ConvOption.UserConvFn option
9593func WithUserConvFn (fn comdef.ToStringFunc ) ConvOptionFn {
9694 return func (opt * ConvOption ) {
@@ -116,11 +114,6 @@ func (opt *ConvOption) WithOption(optFns ...ConvOptionFn) {
116114
117115// ToStringWith try to convert value to string. can with some option func, more see ConvOption.
118116func ToStringWith (in any , optFns ... ConvOptionFn ) (str string , err error ) {
119- opt := NewConvOption (optFns ... )
120- if ! opt .NilAsFail && in == nil {
121- return "" , nil
122- }
123-
124117 switch value := in .(type ) {
125118 case int :
126119 str = strconv .Itoa (value )
@@ -161,6 +154,18 @@ func ToStringWith(in any, optFns ...ConvOptionFn) (str string, err error) {
161154 case error :
162155 str = value .Error ()
163156 default :
157+ if len (optFns ) == 0 && in == nil {
158+ return "" , nil
159+ }
160+
161+ opt := NewConvOption (optFns ... )
162+ if in == nil {
163+ if opt .NilAsFail {
164+ err = comdef .ErrConvType
165+ }
166+ return
167+ }
168+
164169 if opt .HandlePtr {
165170 if rv := reflect .ValueOf (in ); rv .Kind () == reflect .Pointer {
166171 rv = rv .Elem ()
0 commit comments