當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang time.Time.GobEncode()用法及代碼示例

在Go語言中,時間包提供了確定和查看時間的函數。 Go語言中的GobEncode()函數用於實現gob.GobEncoder接口。此外,此函數在時間包下定義。在這裏,您需要導入“time”包才能使用這些函數。

用法:

func (t Time) GobEncode() ([]byte, error)

在此,“t”是指定的時間,在此方法中,將返回“byte”和“error”類型的兩個值作為輸出。

返回值:它返回一個表示接收器編碼的字節片,以便可以將其傳輸到GobDecoder,並且還返回發生錯誤的信息,但是如果沒有錯誤,則返回“nil”。

範例1:



// Golang program to illustrate the usage of 
// Time.GobEncode() 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(2018, 2, 1, 14, 30, 0, 0, time.UTC) 
  
    // Calling GobEncode() method 
    encoding, error:= t.GobEncode() 
  
    // Prints receiver's encoding 
    fmt.Printf("Receiver's encoding:%v\n", encoding) 
  
    // Prints error 
    fmt.Printf("Error occurred:%v\n", error) 
}

輸出:

Receiver's encoding:[1 0 0 0 14 210 5 27 104 0 0 0 0 255 255]
Error occurred:nil

範例2:

// Golang program to illustrate the usage of 
// Time.GobEncode() 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, 37, 43, 76, 90, 88, 5453, time.UTC) 
  
    // Calling GobEncode() method 
    encoding, error:= t.GobEncode() 
  
    // Prints receiver's encoding 
    fmt.Printf("Receiver's encoding:%v\n", encoding) 
  
    // Prints error 
    fmt.Printf("Error occurred:%v\n", error) 
}

輸出:

Receiver's encoding:[1 0 0 0 14 217 157 49 176 0 0 21 77 255 255]
Error occurred:nil

此處,以上代碼中說明的“t”的值不在通常範圍內,但在轉換時已標準化。




相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 time.Time.GobEncode() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。