GO語言"fmt"包中"Stringer"類型的用法及代碼示例。
Stringer 由任何具有 String 方法的值實現,該方法定義了該值的“native” 格式。 String 方法用於將作為操作數傳遞的值打印到任何接受字符串的格式或未格式化的打印機(例如 Print)。
用法:
type Stringer interface {
String() string
}
例子:
package main
import (
"fmt"
)
// Animal has a Name and an Age to represent an animal.
type Animal struct {
Name string
Age uint
}
// String makes Animal satisfy the Stringer interface.
func (a Animal) String() string {
return fmt.Sprintf("%v (%d)", a.Name, a.Age)
}
func main() {
a := Animal{
Name: "Gopher",
Age: 2,
}
fmt.Println(a)
}
輸出:
Gopher (2)
相關用法
- GO Strings用法及代碼示例
- GO StripPrefix用法及代碼示例
- GO StreamWriter用法及代碼示例
- GO StructTag.Lookup用法及代碼示例
- GO StructTag用法及代碼示例
- GO StructOf用法及代碼示例
- GO StreamReader用法及代碼示例
- GO Stmt用法及代碼示例
- GO Stmt.QueryRowContext用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO Split用法及代碼示例
- GO Server.Shutdown用法及代碼示例
- GO Slice用法及代碼示例
- GO SplitAfter用法及代碼示例
- GO Sum256用法及代碼示例
- GO SectionReader用法及代碼示例
- GO Sin用法及代碼示例
- GO Sprintf用法及代碼示例
- GO SendMail用法及代碼示例
- GO Sprint用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Stringer。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。