在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, high:178, name:NewMan
age:10, high:178, 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, 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, high:178, name:NewMan
age:10, high:178, 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, 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, high:178, name:NewMan
age:10, high:178, 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, 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:
{%!s(int=10) %!s(int=178) NewMan}
{10 178 NewMan}
{10 178 NewMan}
此时的输出并不是我们想要的,所以这个用法不可行。