当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Golang time.Time.GobDecode()用法及代码示例

在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的GobDecode()函数用于实现gob.GobDecoder接口。此外,此函数在时间包下定义。在这里,您需要导入“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”的值不在通常范围内,但在转换时已标准化。




相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 time.Time.GobDecode() Function in Golang with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。