Golang time.Time.GobDecode()函数及示例
在Go语言中,time包提供了确定和查看时间的功能。在Go语言中, GobDecode() 函数用于实现gob.GobDecoder接口。此外,该函数在time包中定义。在使用这些函数之前,需要导入“time”包。
语法:
func (t *Time) GobDecode(data []byte) error
在此,”t”是所述时间的指针,”data”是覆盖GobEncode()方法返回的接收器编码的字节片。
返回值: 它会覆盖GobEncode()方法返回的接收器编码并返回发生的错误,但如果没有错误,则返回“nil”。
示例1:
// Golang program to illustrate the usage of
// Time.GobDecode() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Defining t for GobEncode method
t := time.Date(2019, 4, 6, 12, 34, 33, 0, time.UTC)
// Calling GobEncode() method
encoding, error := t.GobEncode()
// If error is not nil then panic error
if error != nil {
panic(error)
}
// Defining tm for GobDecode() method
var tm time.Time
// Calling GobDecode method with its parameters
decode := tm.GobDecode(encoding)
// Prints error
fmt.Printf("Error: %v\n", decode)
}
输出:
Error: <nil>
示例2:
// Golang program to illustrate the usage of
// Time.GobDecode() function
// Including main package
package main
// Importing fmt and time
import "fmt"
import "time"
// Calling main
func main() {
// Defining t for GobEncode method
t := time.Date(2020, 44, 61, 37, 87, 72, 4566, time.UTC)
// Calling GobEncode() method
encoding, error := t.GobEncode()
// If error is not nil then panic error
if error != nil {
panic(error)
}
// Defining tm for GobDecode() method
var tm time.Time
// Calling GobDecode method with its parameters
decode := tm.GobDecode(encoding)
// Prints error
fmt.Printf("Error: %v\n", decode)
}
输出:
Error: <nil>
在此,以上代码中的“t”具有超出正常范围的值,但在转换时它们被规范化。