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

前端 未结 6 1777
既然无缘
既然无缘 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:59

    Generally speaking, it's best to avoid assigning values to variables via static initializers, i.e.

    f := Foo{bar:1,baz:"2"}
    

    This is because it can create exactly the complaint you're talking about, if you forget to pass foo as a pointer via &foo or you decide to use value receivers you end up making a lot of clones of your values.

    Instead, try to assign pointers to static initializers by default, i.e.

    f := &Foo{bar:1,baz:"2"}
    

    This way f will always be a pointer and the only time you'll get a value copy is if you explicitly use value receivers.

    (There are of course times when you want to store the value from a static initializer, but those should be edge cases)

提交回复
热议问题