在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。 Go語言中的fmt.Errorf()函數允許我們使用格式設置函數來創建描述性錯誤消息。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。
用法:
func Errorf(format string, a ...interface{}) error
參數:此函數接受兩個參數,如下所示:
- string:這是您的錯誤消息,帶有占位符值,例如%s表示字符串,%d表示整數。
- a …interface{}:這可以是代碼中使用的常量變量名稱,也可以是任何內置函數。
返回值:它返回字符串作為滿足錯誤的值。
範例1:
// Golang program to illustrate the usage of
// fmt.Errorf() function
// Including the main package
package main
// Importing fmt
import (
"fmt"
)
// Calling main
func main() {
// Declaring some constant variables
const name, dept = "GeeksforGeeks", "CS"
// Calling the Errorf() function with verb
// %q which is used for a single-quoted character
err:= fmt.Errorf("%q is a %q Portal.", name, dept)
// Printing the error message
fmt.Println(err.Error())
}
輸出:
"GeeksforGeeks" is a "CS" Portal.
範例2:
// Golang program to illustrate the usage of
// fmt.Errorf() function
// Including the main package
package main
// Importing fmt and time
import (
"fmt"
"time"
)
// Calling main
func main() {
// Calling Errorf() function with verb $v which is used
// for printing structs
err:= fmt.Errorf("error occurred at:%v", time.Now())
// Printing the error
fmt.Println("An error happened:", err)
}
輸出:
An error happened:error occurred at:2009-11-10 23:00:00 +0000 UTC m=+0.000000001
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 fmt.Errorf() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。