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


Golang log.Panicf()用法及代碼示例

問題解決方法:

在這個程序中,我們將使用 log.Panicf() 函數在控製台屏幕上打印帶時間戳的格式化消息。 log.Panicf() 類似於 log.Printf() 函數,然後調用 Panic() 函數。

程序/源代碼:

下麵給出了演示 log.Panicf() 函數的源代碼。給定的程序在 ubuntu 18.04 操作係統上編譯和執行成功。

// Golang program to demonstrate the
// log.Panicf() function

package main

// Import log package to use
// Panicf() function
import "log"

// Import fmt package to use Println() function
// to print the message on the console screen
import "fmt"

func main() {
	var err int = 32
	log.Panicf("Error number %d", err)
	fmt.Println("Program finished")
}

輸出:

2021/04/20 01:03:41 Error number 32
panic:Error number 32

goroutine 1 [running]:
log.Panicf(0x4c78d3, 0xf, 0xc0000a2f58, 0x1, 0x1)
	/usr/local/go-faketime/src/log/log.go:361 +0xc5
main.main()
	/tmp/sandbox010096975/prog.go:16 +0x85

Program exited:status 2.

說明:

在上麵的程序中,我們聲明了包 main。 main 包用於告訴 Go 語言編譯器必須編譯該包並生成可執行文件。在這裏,我們導入了 "fmt" 包以使用 Println() 函數,我們還導入了 "log" 包以使用 log.Panicf() 函數。

在 main() 函數中,我們使用 log.Panicf() 函數在控製台屏幕上打印帶時間戳的格式化消息。在這裏,我們在控製台屏幕上打印了錯誤編號。

log.Panicf() 類似於 log.Printf() 函數,然後調用 Panic() 函數。

log.Panicf() 函數調用 Panic() 函數,這就是為什麽在上麵的程序中 fmt.Println() 函數沒有在 log.Panicf() 函數之後調用。





相關用法


注:本文由純淨天空篩選整理自 Golang program to demonstrate the log.Panicf() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。