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


Golang fmt.Fprintln()用法及代碼示例

在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。 Go語言格式的fmt.Fprintln()函數使用其操作數的默認格式並寫入w。在此,始終在指定的操作數之間添加空格,並在末尾添加換行符。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。

用法:

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

參數:此函數接受兩個參數,如下所示:

  • 作家這是指定的標準輸入或輸出。
  • a …interface{}:它包含一些代碼中使用的字符串和常量變量。

返回值:它返回已寫入的字節數以及遇到的任何寫入錯誤。

範例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),但仍打印出新行,可以從above-shown輸出中看到。

範例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()函數中,仍未打印任何空格,包括從above-shown輸出中可​​以看到的空格。




相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 fmt.Fprintln() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。