Go語言型態轉字串的作法如下。
型態值轉字串只要該型態實作fmt
package的Stringer
介面的String()
方法簽章即可,因為fmt
或其他函示庫會呼叫此介面來轉成字串。
例如下面的自訂struct Employee
型態實作了Stringer
介面的String()
,則呼叫fmt.Println()
傳入Employee
值時會印出Employee.String()
的返回字串。
package main
import (
"fmt"
"strconv"
)
type Employee struct {
ID int64
Name string
Age int
}
// Employee implments fmt.Stringer's String() method signature
func (e Employee) String() string {
return "Employee={" +
"ID=" + strconv.FormatInt(e.ID, 10) + "," +
"Name=" + e.Name + "," +
"Age=" + strconv.Itoa(e.Age) +
"}"
}
func main() {
employee := Employee{1, "John", 33}
fmt.Println(employee) // Employee={ID=1,Name=John,Age=33}
}
沒有留言:
張貼留言