日期時間函數
// 時間日期函數包
import "time"
// 1. 目前時間 time.Now()-->time.Time類型
// 2. now:=time.Now() now.Year() now.Month() ->May int(now.Month)->5
// 格式化日期時間
// 方式1 Sprintf("%d")配合 now.Year() 傳回格式化字元串
// 方式2 now.Format("2006 01 02 15:04:05") 隻取年now.Format("2006") 這個設計太有意思了
// time.Unix 時間戳 UnixNano 納秒時間戳
func T1() {
// 指定資料建立一個time.Date 注意參數 月份time.October 時間精确到毫秒 時區必須有 UTC/Local
birthday := time.Date(1992, time.June , 1, 12, 20, 58,666, time.Local)
// type is time.Time,value is 1992-06-01 12:20:58.000000666 +0800 CST
fmt.Printf("type is %T,value is %v
", birthday, birthday)
// 日期格式化 Sprintf
strbirthday := fmt.Sprintf("%d年%d月%d日", birthday.Year(), birthday.Month(), birthday.Day())
// type is string,value is 1992年6月1日
fmt.Printf("type is %T,value is %v
", strbirthday, strbirthday)
// 日期格式化 Format
str := birthday.Format("2006/01/02 15:04:05")
// type is string,value is 1992/06/01 12:20:58
fmt.Printf("type is %T,value is %v
", str, str)
}
内建函數
-
傳回序列的長度 string array slice map chanlen(seq)
-
用于配置設定記憶體,主要用于配置設定值類型 --> 傳回的是指針new(type)
-
用于配置設定記憶體,主要用來配置設定引用類型make()
-
抛出錯誤panic()
-
捕獲錯誤recover()
錯誤處理
預設情況下,當發生錯誤(panic)後,程式就會退出(崩潰)
希望可以捕獲錯誤,進行處理,保證程式可以繼續執行,需要一個處理錯誤的機制
golang錯誤處理機制
panic +defer + recover
程式抛出panic異常,defer中通過recover捕獲這個異常,然後進行處理
defer func () { // defer + 匿名函數 + revocer
err := recover() //内置函數 可以捕獲到異常
if err != nil {
fmt.Println(err) // 列印錯誤
// dosomething
}
}()
自定義錯誤
- errors.New("錯誤說明") 傳回一個error類型 表示一個錯誤
- panic()可以接受interface{}類型的值作為參數,可以接受error類型的變量,輸出錯誤資訊,并退出程式