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


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

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

用法:

func Println(a ...interface{}) (n int, err error)

在此,“ a…interface {}”包含一些字符串,其中包括指定的常量變量。

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

範例1:



// Golang program to illustrate the usage of 
// fmt.Println() function 
  
// Including the main package 
package main 
  
// Importing fmt 
import ( 
    "fmt"
) 
  
// Calling main 
func main() { 
  
    // Declaring some const variables 
    const name, dept = "GeeksforGeeks", "CS"
  
    // Calling Println() function 
    fmt.Println(name, "is", "a", dept, "Portal.") 
  
    // It is conventional not to worry about any 
    // error returned by Println. 
  
}

輸出:

GeeksforGeeks is a CS Portal.

在上麵的代碼中,可以看出函數Println()在指定字符串中不包含任何空格,仍然可以從上麵的輸出中看出是輸出的打印空間。

範例2:

// Golang program to illustrate the usage of 
// fmt.Println() function 
  
// Including the main package 
package main 
  
// Importing fmt 
import ( 
    "fmt"
) 
  
// Calling main 
func main() { 
  
    // Declaring some const variables 
    const num1, num2, num3, num4 = 5, 10, 15, 50 
  
    // Calling Println() function 
    fmt.Println(num1, "+", num2, "=", num3) 
    fmt.Println(num1, "*", num2, "=", num4) 
  
    // It is conventional not to worry about any 
    // error returned by Println. 
  
}

輸出:

5 + 10 = 15
5 * 10 = 50

在上麵的代碼中,可以看出函數Println()仍未在輸出中使用任何換行符(\ n),它會打印出新行,該行可以從上麵顯示的輸出中看到。




相關用法


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