Go的encoding package定義數個資料轉換的介面,包括byte及文字(text)的轉換,並被用於其他轉換資料的package包括encoding/json、encoding/gob、encoding/xml,也就是說實作encoding的介面即可用於多種資料格式的轉換。Go的time.Time及net.IP皆實作這些介面。
下面自訂Date型態為time.Time並實作encoding的TextMarshaler、TextUnmarshaler介面來定義Date與文字間的轉換。
範例環境:
- Go 1.17
範例
下面定義Date為time.Time。
Date實作TextMarshaler介面的MarshalText()定義如何轉換Date為string。
Date實作TextUnmarshaler介面的UnmarshalText()定義如何轉換string為Date。
調用encoding/json的Marshal()及Unmarshal()轉換Date時便會依上面的實作進行。
package main
import (
"encoding/json"
"fmt"
"time"
)
var df = "2006-01-02"
type Date time.Time
// current local date
func NewDate() Date {
return Date(time.Now())
}
// string to Date
func (d *Date) UnmarshalText(text []byte) error {
t, err := time.Parse(df, string(text))
if err != nil {
return err
}
*d = Date(t)
return nil
}
// Date to string
func (d Date) MarshalText() (text []byte, err error) {
s := time.Time(d).Format(df)
return []byte(s), nil
}
func (d Date) String() string {
return time.Time(d).Format(df)
}
func main() {
t := time.Now()
fmt.Println(t) // 2022-03-04 12:39:08.360021 +0800 CST m=+0.000235750
d := Date(t)
fmt.Println(d) // 2022-03-04
b, _ := json.Marshal(d)
s := string(b)
fmt.Println(s) // "2022-03-04"
json.Unmarshal([]byte(s), &d)
fmt.Println(d) // 2022-03-04
}
沒有留言:
張貼留言