当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Golang fmt.Fprintf()用法及代码示例

在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)

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

  • 作家这是指定的标准输入或输出。
  • format string:它包含一些字符串,包括动词。
  • 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 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) 
  
}

输出:

GeeksforGeeks is a CS portal.
30 bytes written.
<nil>

范例2:

// 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.
<nil>



相关用法


注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 fmt.Fprintf() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。