Golang fmt.Fprintln()函数及示例
在Go语言中,fmt包使用类似于C的printf()和scanf()函数的函数实现格式化的输入/输出。Go语言中的fmt.Fprintln()函数使用其操作数的默认格式进行格式化并写入w。在此,指定的操作数之间始终添加空格,并在末尾附加换行符。此外,该函数在fmt包中定义。在这里,您需要导入“fmt”包以使用这些函数。
Syntax:
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
Parameters: 该函数接受下面两个参数:
- w io.Writer: 这是指定的标准输入或输出。
- a …interface{}: 这是包含在代码中使用的一些字符串和常量变量。
Return Value: 该函数返回写入的字节数以及遇到的任何写入错误。
示例1:
// Golang program to illustrate the usage of
// fmt.Fprintln() function
// Including the main package
package main
// Importing fmt and os
import (
"fmt"
"os"
)
// Calling main
func main() {
// Declaring some const variables
const name, dept = "GeeksforGeeks", "CS"
// Calling Fprintln() function which returns
// "n" as the number of bytes written and
// "err" as any error ancountered
n, err := fmt.Fprintln(os.Stdout, name,
"is a", dept, "portal.")
// Printing the number of bytes written
fmt.Print(n, " bytes written.\n")
// Printing if any error encountered
fmt.Print(err)
}
输出:
GeeksforGeeks is a CS portal.
30 bytes written.
<nil>
在上面的代码中,可以看到在Fprintln()函数中没有添加换行符(\n),但它仍打印出了一个新行,这可以从上面的输出中看到。
示例2:
// Golang program to illustrate the usage of
// fmt.Fprintln() function
// Including the main package
package main
// Importing fmt and os
import (
"fmt"
"os"
)
// Calling main
func main() {
// Declaring some const variables
const str1, str2, str3 = "a", "b", "c"
// Calling Fprintln() function which returns
// "n" as the number of bytes written and
// "err" as any error ancountered
n, err := fmt.Fprintln(os.Stdout, str1, str2, str3)
// Printing the number of bytes written
fmt.Print(n, " bytes written.\n")
// Printing if any error encountered
fmt.Print(err)
}
输出:
a b c
6 bytes written.
<nil>
在上面的代码中,可以看到在Fprintln()函数中没有添加空格,但它仍打印一个包括空格的字符串,这可以从上面的输出中看到。
极客教程