【发布时间】:2017-06-17 08:49:21
【问题描述】:
在 php 中存在一个 __toString() 方法,允许对对象进行 taylored 表示。例如:
final class Foo
{
public function __toString()
{
return "custom representation";
}
}
$foo = new Foo();
echo $foo; // this will output "custom representation"
在 Go 中可以创建一个结构:
type Person struct {
surname string
name string
}
sensorario := Person{
"Senso",
"Rario",
}
fmt.Println(sensorario) // this will output "{Senso Rario}"
可以在结构体中添加 toString 方法吗?
编辑:
我找到了这个解决方案:
func (p *Person) toString() string {
return p.surname + " " + p.name
}
fmt.Println(simone.toString())
但我正在寻找的,是替换的方式
fmt.Println(simone.toString())
与
fmt.Println(simone)
【问题讨论】:
标签: go