Golang fmt.Sprintf()函数及示例

Golang fmt.Sprintf()函数及示例

在Go语言中,fmt包是基于C语言的printf()和scanf()函数实现的一系列格式输入输出功能。Go语言中的 fmt.Sprintf() 函数会根据格式说明符进行格式设置,并返回结果字符串。此外,此函数是在fmt包中定义的。在此,需要导入“fmt”包以使用这些函数。

语法:

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

参数: 本函数接受以下两个参数:

  • 格式字符串: 包含一些变量和一些字符串。
  • 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程