1
0
mirror of https://github.com/golang/go synced 2024-11-13 16:20:21 -07:00

fmt: handle os.Error values

Handling os.Error is no different than handling fmt.Stringer
here, so the code is redundant now, but it will be necessary
once error goes in.

Adding it now will make gofix fix it.

R=r
CC=golang-dev
https://golang.org/cl/5331045
This commit is contained in:
Russ Cox 2011-10-27 21:20:44 -07:00
parent 853c84631f
commit 0e81e508be
2 changed files with 21 additions and 6 deletions

View File

@ -89,10 +89,14 @@
If an operand implements interface Formatter, that interface If an operand implements interface Formatter, that interface
can be used for fine control of formatting. can be used for fine control of formatting.
If an operand implements method String() string that method Next, if an operand implements the error interface, the Error method
will be used to convert the object to a string, which will then will be used to convert the object to a string, which will then
be formatted as required by the verb (if any). To avoid be formatted as required by the verb (if any).
recursion in cases such as
Finally, if an operand implements method String() string that method
will be used to convert the object to a string, which will then
be formatted as required by the verb (if any).
To avoid recursion in cases such as
type X int type X int
func (x X) String() string { return Sprintf("%d", x) } func (x X) String() string { return Sprintf("%d", x) }
cast the value before recurring: cast the value before recurring:

View File

@ -630,12 +630,23 @@ func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString
return return
} }
} else { } else {
// Is it a Stringer? // Is it an error or Stringer?
if stringer, ok := p.field.(Stringer); ok { // The duplication in the bodies is necessary:
// setting wasString and handled and deferring catchPanic
// must happen before calling the method.
switch v := p.field.(type) {
case os.Error:
wasString = false wasString = false
handled = true handled = true
defer p.catchPanic(p.field, verb) defer p.catchPanic(p.field, verb)
p.printField(stringer.String(), verb, plus, false, depth) p.printField(v.String(), verb, plus, false, depth)
return
case Stringer:
wasString = false
handled = true
defer p.catchPanic(p.field, verb)
p.printField(v.String(), verb, plus, false, depth)
return return
} }
} }