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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。