Go语言爱好者周刊:第 119 期

polaris · · 5447 次点击
polaris
社区,需要你我一同完善!
看下 fmt.Stringer 接口
#2
更多评论
求解为什么运行String()
#1
<a href="/user/polaris" title="@polaris">@polaris</a> 我在微信里看到有人说是handleMethods调用的String(),但是我看不懂那些单个字母表示什么 ```go func (p *pp) handleMethods(verb rune) (handled bool) { if p.erroring { return } if verb == &#39;w&#39; { // It is invalid to use %w other than with Errorf, more than once, // or with a non-error arg. err, ok := p.arg.(error) if !ok || !p.wrapErrs || p.wrappedErr != nil { p.wrappedErr = nil p.wrapErrs = false p.badVerb(verb) return true } p.wrappedErr = err // If the arg is a Formatter, pass &#39;v&#39; as the verb to it. verb = &#39;v&#39; } // Is it a Formatter? if formatter, ok := p.arg.(Formatter); ok { handled = true defer p.catchPanic(p.arg, verb, &#34;Format&#34;) formatter.Format(p, verb) return } // If we&#39;re doing Go syntax and the argument knows how to supply it, take care of it now. if p.fmt.sharpV { if stringer, ok := p.arg.(GoStringer); ok { handled = true defer p.catchPanic(p.arg, verb, &#34;GoString&#34;) // Print the result of GoString unadorned. p.fmt.fmtS(stringer.GoString()) return } } else { // If a string is acceptable according to the format, see if // the value satisfies one of the string-valued interfaces. // Println etc. set verb to %v, which is &#34;stringable&#34;. switch verb { case &#39;v&#39;, &#39;s&#39;, &#39;x&#39;, &#39;X&#39;, &#39;q&#39;: // Is it an error or Stringer? // The duplication in the bodies is necessary: // setting handled and deferring catchPanic // must happen before calling the method. switch v := p.arg.(type) { case error: handled = true defer p.catchPanic(p.arg, verb, &#34;Error&#34;) p.fmtString(v.Error(), verb) return case Stringer: handled = true defer p.catchPanic(p.arg, verb, &#34;String&#34;) p.fmtString(v.String(), verb) return } } } return false } ```
#3