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

前端 未结 6 1787
既然无缘
既然无缘 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条回答
  •  感动是毒
    2020-12-12 16:47

    Methods

    Pointers vs. Values

    The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver; invoking them on a copy of the value would cause those modifications to be discarded.

    Therefore, for your String method to work when invoked on both pointers and values, use a value receiver. For example,

    package main
    
    import "fmt"
    
    type Car struct {
        year int
        make string
    }
    
    func (c Car) String() string {
        return fmt.Sprintf("{make:%s, year:%d}", c.make, c.year)
    }
    
    func main() {
        myCar := Car{year: 1996, make: "Toyota"}
        fmt.Println(myCar)
        fmt.Println(&myCar)
    }
    

    Output:

    {make:Toyota, year:1996}
    {make:Toyota, year:1996}
    

提交回复
热议问题