有没有Go语言的等价物来实现PHP的__toString方法?

huangapple go评论79阅读模式
英文:

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

问题

在PHP中存在一个__toString()方法,允许自定义对象的表示形式。例如:

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

$foo = new Foo();
echo $foo; // 这将输出 "custom representation"

在Go语言中,可以创建一个结构体:

type Person struct {
    surname string
    name    string
}

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

fmt.Println(sensorario) // 这将输出 "{Senso Rario}"

是否可以为结构体添加一个toString方法?


编辑:

我找到了这个解决方案:

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

fmt.Println(simone.toString())

但是我想知道的是,如何将

fmt.Println(simone.toString())

替换为

fmt.Println(simone)
英文:

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)

答案1

得分: 4

我认为你正在寻找Stringer接口。

type Stringer interface {
    String() string
}

任何实现了这个接口的类型都会被许多不同的库自动转换为字符串,包括fmt包,因此在你的fmt.Println示例中确实可以工作。

英文:

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.

huangapple
  • 本文由 发表于 2017年6月17日 16:49:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/44602568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定