go结构体重写String方法从而自定义打印内容

package main

import "fmt"

type student struct {
	name string
	age  int
}

func (s student) String() string {
	return fmt.Sprintf("{name is %s, age is %d}", s.name, s.age)
}

func main() {
	s := student{
		name: "a",
		age:  17,
	}
	fmt.Printf("%v %+v\n", s, s)
}

没有String方法

相比于%v,%+v打印时会显示结构体属性。

有String方法,覆盖了%v和%+v默认输出。
有String方法,fmt.Printf("%s\n", s)输出结果与%v %+v相同。

posted on 2024-04-08 22:22  王景迁  阅读(5)  评论(0编辑  收藏  举报

导航