當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Stringer用法及代碼示例

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)

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Stringer。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。