在python中,可以通过__str__()定义输出对象的信息。同样的,在Go中Stringer接口也有此功能。Stringer接口定义在fmt包中,该接口包含String()函数。任何类型只要定义了String()函数,进行Print输出时,就可以得到定制输出。
Stringer接口定义如下:
type Stringer interface { String() string }
下面通过一些例子加以说明。
example1
package main
import (
"fmt"
)
type Power struct{
age int
high int
name string
}
//指针类型
func (this *Power) String() string {
return fmt.Sprintf("age:%d,high:%d,name:%s",this.age,this.high,this.name)
}
func main() {
var i *Power = &Power{age: 10,high: 178,name: "NewMan"} //指针类型
fmt.Printf("%s\n",i)
fmt.Println(i)
fmt.Printf("%v",i)
}
output:
age:10,high:178,name:NewMan
age:10,name:NewMan
example2
package main
import (
"fmt"
)
type Power struct{
age int
high int
name string
}
//非指针
func (this Power) String() string {
return fmt.Sprintf("age:%d,this.name)
}
func main() {
var i Power = Power{age: 10,name: "NewMan"} //非指针变量
fmt.Printf("%s\n",name:NewMan
example3
package main
import (
"fmt"
)
type Power struct{
age int
high int
name string
}
//非指针类型
func (this Power) String() string {
return fmt.Sprintf("age:%d,name: "NewMan"}//指针类型
fmt.Printf("%s\n",name:NewMan
example4
package main
import (
"fmt"
)
type Power struct{
age int
high int
name string
}
//指针类型
func (this *Power) String() string {
return fmt.Sprintf("age:%d,this.name)
}
func main() {
var i Power = Power{age: 10,name: "NewMan"} //非指针
fmt.Printf("%s\n",i)
}
output:
{%!s(int=10) %!s(int=178) NewMan}
{10 178 NewMan}
{10 178 NewMan}
原文链接:https://www.f2er.com/go/187867.html