fmt.Sprintln() Function in Golang With Examples

In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprintln() function in Go language formats using the default formats for its operands and returns the resulting string. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.

Syntax:

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

Here, “a …interface{}” is containing some strings along with the specified constant variables.

Returns: It returns the resulting string.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
  
}

chevron_right


Output:

GeeksforGeeks is a CS Portal.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
  
}

chevron_right


Output:

5 + 10 = 15
5 * 10 = 50

In the above code, no new line or space is used still this function append new line and space between the operands that can be seen in the above output.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.