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

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

在 Go 语言中, fmt包使用类似于 C 的 printf() 和 scanf()函数的函数来实现格式化的 I/O。 Go 语言格式的fmt.Fprint()函数使用其操作数的默认格式并写入 w。这里当任何字符串不用作参数时,在操作数之间添加空格。而且,这个函数是在 fmt 包下定义的。在这里,您需要导入“fmt”包才能使用这些功能。

句法:

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

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

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

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

示例 1:

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

// Golang program to illustrate the usage of
// fmt.Fprint() 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 = "a", "b", "c"
  
    // Calling Fprint() function which returns
    // "n" as the number of bytes written and
    // "err" as any error encountered
    n, err := fmt.Fprint(os.Stdout, num1, num2, num3, "\n")
  
    // Printing the number of bytes written
    fmt.Print(n, " bytes written.\n")
  
    // Printing if any error encountered
    fmt.Print(err)
  
}

输出:

abc
4 bytes written.

在上面的代码中,使用的常量变量是字符串,因此在输出中显示的两个字符串之间没有添加空格。

示例 3:

// Golang program to illustrate the usage of
// fmt.Fprint() 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, 15, 15
  
    // Calling Fprint() function which returns
    // "n" as the number of bytes written and 
    // "err" as any error encountered
    n, err := fmt.Fprint(os.Stdout, num1, num2, num3, "\n")
  
    // Printing the number of bytes written
    fmt.Print(n, " bytes written.\n")
  
    // Printing if any error encountered
    fmt.Print(err)
  
}

输出:

5 15 15
8 bytes written.

在上面的代码中,使用的常量变量是数字,因此在输出中显示的两个数字之间添加了空格。