英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论