GO语言"fmt"包中"GoStringer"类型的用法及代码示例。
GoStringer 由任何具有 GoString 方法的值实现,该方法定义了该值的 Go 语法。 GoString 方法用于将作为操作数传递的值打印为 %#v 格式。
用法:
type GoStringer interface {
GoString() string
}
例子:
package main
import (
"fmt"
)
// Address has a City, State and a Country.
type Address struct {
City string
State string
Country string
}
// Person has a Name, Age and Address.
type Person struct {
Name string
Age uint
Addr *Address
}
// GoString makes Person satisfy the GoStringer interface.
// The return value is valid Go code that can be used to reproduce the Person struct.
func (p Person) GoString() string {
if p.Addr != nil {
return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country)
}
return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age))
}
func main() {
p1 := Person{
Name: "Warren",
Age: 31,
Addr: &Address{
City: "Denver",
State: "CO",
Country: "U.S.A.",
},
}
// If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to
// Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}
fmt.Printf("%#v\n", p1)
p2 := Person{
Name: "Theia",
Age: 4,
}
// If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to
// Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)}
fmt.Printf("%#v\n", p2)
}
输出:
Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}} Person{Name: "Theia", Age: 4}
相关用法
- GO Getenv用法及代码示例
- GO Get用法及代码示例
- GO PutUvarint用法及代码示例
- GO Scanner.Scan用法及代码示例
- GO LeadingZeros32用法及代码示例
- GO NewFromFiles用法及代码示例
- GO Regexp.FindString用法及代码示例
- GO Time.Sub用法及代码示例
- GO Regexp.FindAllIndex用法及代码示例
- GO Encode用法及代码示例
- GO ResponseRecorder用法及代码示例
- GO Value用法及代码示例
- GO StreamWriter用法及代码示例
- GO Fscanln用法及代码示例
- GO Values.Get用法及代码示例
- GO NumError用法及代码示例
- GO TrailingZeros8用法及代码示例
- GO Logger.Output用法及代码示例
- GO Float.SetString用法及代码示例
- GO NewReader用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 GoStringer。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。