doujing2017 2017-06-17 08:49
浏览 56
已采纳

Go等同于PHP的__toString方法吗?

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条回答 默认 最新

  • douyu9159 2017-06-17 09:33
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)