網頁

2021/7/3

Golang Stringer轉字串 to string

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}
}


沒有留言:

張貼留言