sensorario
sensorario

Reputation: 21600

Is there a Go equivalent of PHP's __toString method?

In php exists a __toString() method that allow to make a taylored representation of an object. For example:

final class Foo
{
    public function __toString()
    {
        return "custom representation";
    }
}

$foo = new Foo();
echo $foo; // this will output "custom representation"

In Go it is possible to create a struct:

type Person struct {
    surname string
    name    string
}

sensorario := Person{
    "Senso",
    "Rario",
}

fmt.Println(sensorario) // this will output "{Senso Rario}"

It is possible to add a toString method to the struct?


EDIT:

I've found this solution:

func (p *Person) toString() string {
    return p.surname + " " + p.name
}

fmt.Println(simone.toString())

But what I am looking for, is the way to replace

fmt.Println(simone.toString())

with

fmt.Println(simone)

Upvotes: 1

Views: 304

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79516

I think you're looking for the Stringer interface.

type Stringer interface {
    String() string
}

Any type that implements this interface will be automatically stringified using it by many different libraries, obviously including the fmt package, and will indeed work in your example of fmt.Println.

Upvotes: 4

Related Questions