Golang fmt.Sprintln() 函数及示例

Golang fmt.Sprintln() 函数及示例

Go 语言中,fmt 包实现了类似于 C 语言的 printf() 和scanf() 函数的格式化 I/O,其中 fmt.Sprintln() 函数使用其操作数的默认格式进行格式化,并返回结果字符串。在此函数中,操作数之间始终添加空格,并在结尾附加换行符。此外,此函数是在 fmt 包下定义的。在此处,需要导入“fmt”包才能使用这些函数。

语法:

func Sprintln(a ...interface{}) string

在此语法中,“a…interface{}”包含一些字符串以及指定的常量变量。

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

示例1:

// Golang program to illustrate the usage of
// fmt.Sprintln() 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 Sprintln() function
    s := fmt.Sprintln(name, "is a", dept, "Portal.")
  
    // Calling WriteString() function to write the
    // contents of the string "s" to "os.Stdout"
    io.WriteString(os.Stdout, s)
  
} 

输出:

GeeksforGeeks 是 CS 门户网站。

示例2:

// Golang program to illustrate the usage of
// fmt.Sprintln() 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, num4 = 5, 10, 15, 50
  
    // Calling Sprintln() function
    s1 := fmt.Sprintln(num1, "+", num2, "=", num3)
    s2 := fmt.Sprintln(num1, "*", num2, "=", num4)
  
    // Calling WriteString() function to write the
    // contents of the string "s1" and "s2" to "os.Stdout"
    io.WriteString(os.Stdout, s1)
    io.WriteString(os.Stdout, s2)
  
} 

输出:

5 + 10 = 15
5 * 10 = 50

在上面的代码中,没有使用换行符或空格,但是此函数在操作数之间添加了换行符和空格,可以在上面的输出中看到。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程