Why isn't my Stringer interface method getting invoked? When using fmt.Println

前端 未结 6 1788
既然无缘
既然无缘 2020-12-12 16:31

Suppose I have the following code:

package main

import \"fmt\"

type Car struct{
    year int
    make string
}

func (c *Car)String() string{
    return fm         


        
6条回答
  •  猫巷女王i
    2020-12-12 16:45

    It's only related to implementation of fmt instead of Go however.

    String() with pointer receiver would be invoked by https://github.com/davecgh/go-spew since spew print things in this way:

    v = reflect.ValueOf(arg)
    
    ...
    
    switch iface := v.Interface().(type) {
        case fmt.Stringer:
            defer catchPanic(w, v)
            if cs.ContinueOnMethod {
                w.Write(openParenBytes)
                w.Write([]byte(iface.String()))
                w.Write(closeParenBytes)
                w.Write(spaceBytes)
                return false
            }
            w.Write([]byte(iface.String()))
            return true
        }
    

提交回复
热议问题