Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

引用

像其他语言都有对应的函数可以打印对象的描述
比如Java中的String(),Python中str()
Golang 中是否有对应的用法呢
答案是有的

说明

在Golang中,类只要实现了String(),在执行format时,就会自动调用这个方法。

If an operand implements method String() string, that method >will be invoked to convert the object to a string, which will then >be formatted as required by the verb (if any).

For compound operands such as slices and structs, the format applies to the elements of each operand, recursively, not to the operand as a whole. Thus %q will quote each element of a slice of strings, and %6.2f will control formatting for each element of a floating-point array.

看下面的例子
test_fmt.go

import (
    "fmt"
)

type Car struct{
    age int
    name string

}

func(c Car)String() string {
    return  fmt.Sprintf("Car-[name:%v, age:%v]", c.name, c.age)
}

func main(){
    c1 := Car{age:2, name:"buick"}
    c2 := Car{age:1, name:"benz"}
    fmt.Println(c1)
    // 对于切片中的对象,也能递归调用String()
    carSlice := []Car{}
    carSlice = append(carSlice, c1)
    carSlice = append(carSlice, c2)
    fmt.Println(carSlice)
}

输出

Car-[name:buick, age:2]
[Car-[name:buick, age:2] Car-[name:benz, age:1]]

参考资料

  1. fmt库

请我喝瓶饮料

微信支付码

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据