golang fmt.Stringer 接口的使用

在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}

此时的输出并不是我们想要的,所以这个用法不可行。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值