博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用 String() 方法自定义类型的输出 golang
阅读量:3987 次
发布时间:2019-05-24

本文共 1097 字,大约阅读时间需要 3 分钟。

对于结构体,有时候我们需要打印它的信息,但是打印出来是这样的:

type Family struct {
Father string Mather string Brother string}func main() {
f := Family{
"fa", "ma", "bro"} fmt.Println(f)}

输出:

{fa ma bro}

并不是很直观,golang允许你通过实现 String() 接口来自定义输出。

type Family struct {
Father string Mather string Brother string}func main() {
f := Family{
"fa", "ma", "bro"} fmt.Println(f)}func (f Family) String() string {
return "Father: " + f.Father + "\nMather: " + f.Mather + "\nBrother: " + f.Brother}

输出:

Father: fa
Mather: ma
Brother: bro

或者使用引用的方式

type Family struct {
Father string Mather string Brother string}func main() {
f := &Family{
"fa", "ma", "bro"} fmt.Println(f)}func (f *Family) String() string {
return "Father: " + f.Father + "\nMather: " + f.Mather + "\nBrother: " + f.Brother}

如果类型定义了 String() 方法,它会被用在 fmt.Printf() 中生成默认的输出:等同于使用格式化描述符 %v 产生的输出。还有 fmt.Print() 和 fmt.Println() 也会自动使用 String() 方法。

不要在 String() 方法里面调用涉及 String() 方法的方法,它会导致意料之外的错误,比如无限递归调用。

类似于这样:

func (t TT) String() string {
return fmt.Sprintf("%v", t)}

也很好理解,因为 fmt.Sprintf 又会去再次调用 String(),从而形成无限递归。

转载地址:http://jnaui.baihongyu.com/

你可能感兴趣的文章
[LeetCode By Python]171. Excel Sheet Column Number
查看>>
[LeetCode By Python]172. Factorial Trailing Zeroes
查看>>
[LeetCode By MYSQL] Combine Two Tables
查看>>
Mac删除文件&文件夹
查看>>
python jieba分词模块的基本用法
查看>>
[CCF BY C++]2017.12 最小差值
查看>>
[CCF BY C++]2017-12 游戏
查看>>
《Fluent Python》第三章Dictionaries and Sets
查看>>
如何打开ipynb文件
查看>>
[Leetcode BY python ]190. Reverse Bits
查看>>
面试---刷牛客算法题
查看>>
Android下调用收发短信邮件等(转载)
查看>>
Android中电池信息(Battery information)的取得
查看>>
SVN客户端命令详解
查看>>
Android/Linux 内存监视
查看>>
Linux系统信息查看
查看>>
用find命令查找最近修改过的文件
查看>>
Android2.1消息应用(Messaging)源码学习笔记
查看>>
在android上运行native可执行程序
查看>>
Phone双模修改涉及文件列表
查看>>