On Fri, Oct 7, 2016 at 4:18 PM, sbkim via golang-nuts
<golang-nuts@googlegroups.com> wrote:
>
> If an operand of fmt.Printf implements method String() string, fmt.Printf
> respects it and uses it.
> But it doesn't if an operand is a a struct that has such an element.
>
> For example, https://play.golang.org/p/QJC7Q9Kpch:
> package main
>
> import "fmt"
>
> type Int int
>
> func (i Int) String() string { return fmt.Sprintf("Int(%d)", int(i)) }
>
> type Box struct{ elem Int }
>
> func main() {
>  format := "%[1]v\t%+[1]v\t%#[1]v\n"
>  i := Int(73)
>  fmt.Printf(format, i)
>  fmt.Printf(format, &Box{i})
>  fmt.Printf(format, []Int{i})
>  fmt.Printf(format, map[string]Int{"hello":i})
> }
>
> Output:
> Int(73) Int(73) 73
> &{73} &{elem:73} &main.Box{elem:73}
> [Int(73)] [Int(73)] []main.Int{73}
> map[hello:Int(73)] map[hello:Int(73)] map[string]main.Int{"hello":73}
>
> In the second line of the output, none of the format specifiers ("%v",
> "%+v", "%#v") calls the String() method of Int, in contrast to the first
> line.
>
> Isn't this an inconsistency that should be fixed? Or is it intended
> behavior?

It does seem like a bug.  Please open a bug report at
https://golang.org/issue .  Thanks.

It is happening because of how the reflect package handles unexported
fields.  If you change the field name from elem to Elem I think you
will get the results you expect.  But that is pretty hard to justify.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to