📜  Golang 中的 fmt.Fprintf()函数示例

📅  最后修改于: 2021-10-25 02:32:42             🧑  作者: Mango

在 Go 语言中, fmt包使用类似于 C 的 printf() 和 scanf()函数的函数来实现格式化的 I/O。 Go 语言中的fmt.Fprintf()函数根据格式说明符格式化并写入 w。而且,这个函数是在 fmt 包下定义的。在这里,您需要导入“fmt”包才能使用这些功能。

句法:

func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)

参数:此函数接受三个参数,如下所示 –

  • w io.Writer:这是指定的标准输入或输出。
  • 格式字符串:这包含一些字符串,包括动词。
  • a …interface{}:这是代码中使用的指定常量变量。

返回值:它返回写入的字节数和遇到的任何写入错误。
示例 1:

C
// Golang program to illustrate the usage of
// fmt.Fprintf() 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 Fprintf() function which returns
    // "n" as the number of bytes written and
    // "err" as any error ancountered
    n, err := fmt.Fprintf(os.Stdout, "%s is a %s portal.\n",
                                                name, dept)
 
    // Printing the number of bytes written
    fmt.Print(n, " bytes written.\n")
 
    // Printing if any error encountered
    fmt.Print(err)
 
}


C
// Golang program to illustrate the usage of
// fmt.Fprintf() function
 
// Including the main package
package main
 
// Importing fmt and os
import (
    "fmt"
    "os"
)
 
// Calling main
func main() {
 
    // Declaring some const variables
    const num1, num2, num3 = 5, 10, 15
 
    // Calling Fprintf() function which returns
    // "n" as the number of bytes written and
    // "err" as any error encountered
    n, err := fmt.Fprintf(os.Stdout, "%d + %d = %d.\n",
                                      num1, num2, num3)
 
    // 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.

示例 2:

C

// Golang program to illustrate the usage of
// fmt.Fprintf() function
 
// Including the main package
package main
 
// Importing fmt and os
import (
    "fmt"
    "os"
)
 
// Calling main
func main() {
 
    // Declaring some const variables
    const num1, num2, num3 = 5, 10, 15
 
    // Calling Fprintf() function which returns
    // "n" as the number of bytes written and
    // "err" as any error encountered
    n, err := fmt.Fprintf(os.Stdout, "%d + %d = %d.\n",
                                      num1, num2, num3)
 
    // Printing the number of bytes written
    fmt.Print(n, " bytes written.\n")
 
    // Printing if any error encountered
    fmt.Print(err)
 
}

输出:

5 + 10 = 15.
13 bytes written.