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


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

在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。根據格式說明符使用Go語言格式的fmt.Sprintf()函數,並返回結果字符串。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。

用法:

func Sprintf(format string, a ...interface{}) string

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

  • format string:其中包括一些varb和一些字符串。
  • a …interface{}:這是指定的常量變量。

返回值:它返回結果字符串。

範例1:



// Golang program to illustrate the usage of 
// fmt.Sprintf() function 
  
// Including the main package 
package main 
  
// Importing fmt, io and os 
import ( 
    "fmt"
    "io"
    "os"
) 
  
// Calling main 
func main() { 
  
    // Declaring some const variables 
    const name, dept = "GeeksforGeeks", "CS"
  
    // Calling Sprintf() function 
    s:= fmt.Sprintf("%s is a %s Portal.\n", name, dept) 
  
    // Calling WriteString() function to write the 
    // contents of the string "s" to "os.Stdout" 
    io.WriteString(os.Stdout, s) 
  
}

輸出:

GeeksforGeeks is a CS Portal.

範例2:

// Golang program to illustrate the usage of 
// fmt.Sprintf() function 
  
// Including the main package 
package main 
  
// Importing fmt, io and os 
import ( 
    "fmt"
    "io"
    "os"
) 
  
// Calling main 
func main() { 
  
    // Declaring some const variables 
    const num1, num2, num3 = 5, 10, 15 
  
    // Calling Sprintf() function 
    s:= fmt.Sprintf("%d + %d = %d", num1, num2, num3) 
  
    // Calling WriteString() function to write the 
    // contents of the string "s" to "os.Stdout" 
    io.WriteString(os.Stdout, s) 
  
}

輸出:

5 + 10 = 15



相關用法


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