标准库fmt包中定义了
// Stringer is implemented by any value that has a String method,
// which defines the ``native'' format for that value.
// The String method is used to print values passed as an operand
// to any format that accepts a string or to an unformatted printer
// such as Print.
type Stringer interface {
String() string
}
任何对象定义了String方法,即可以Stringer 类型,fmt、log 进行print输出时会识别为Stringer类型,调用String 方法进行打印输出,即我们可以利用String来进行定制化输出。
示例一 结构体Marshal打印
对于结构体打印,直接调用Println,只能打印其值,如下。
示例代码:
package main
import (
"log"
)
type test struct {
X string
Y int
}
func main() {
a := test{X: "test", Y: 11}
log.Println(a)
}
输出:
2019/03/20 13:04:06 {test 11}
现定义String方法,实现Marshal打印
示例代码:
package main
import (
"encoding/json"
"log"
)
type test struct {
X string
Y int
}
func (test test) String() string {
out, err := json.Marshal(test)
if err != nil {
return err.Error()
}
return string(out)
}
func main() {
a := test{X: "test", Y: 11}
log.Println(a)
}
输出结果
2019/03/20 13:08:02 {"X":"test","Y":11}
示例二 指针打印其指向内容
示例代码:
package main
import (
"log"
)
type test struct {
X string
Y int
}
func main() {
a := &test{X: "a", Y: 1}
b := &test{X: "b", Y: 12}
var testarr []*test
testarr = append(testarr, a)
testarr = append(testarr, b)
log.Println(testarr)
}
输出:
2019/03/20 13:14:06 [0xc042002440 0xc042002460]
现定义String方法,实现打印指针内容
示例代码:
package main
import (
"encoding/json"
"log"
)
type test struct {
X string
Y int
}
func (test test) String() string {
out, err := json.Marshal(test)
if err != nil {
return err.Error()
}
return string(out)
}
func main() {
a := &test{X: "a", Y: 1}
b := &test{X: "b", Y: 12}
var testarr []*test
testarr = append(testarr, a)
testarr = append(testarr, b)
log.Println(testarr)
}
输出结果:
2019/03/20 13:15:03 [{"X":"a","Y":1} {"X":"b","Y":12}]
有疑问加站长微信联系(非本文作者)