fmt.Sprint() Function in Golang With Examples
Last Updated :
05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprint() function in Go language formats using the default formats for its operands and returns the resulting string. Here spaces are added between operands when any string is not used as a constant variable. 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 Sprint(a ...interface{}) string
Here, “a …interface{}” contains some strings including specified constant variables.
Returns: It returns the resulting string.
Example 1:
package main
import (
"fmt"
"io"
"os"
)
func main() {
const name, dept = "GeeksforGeeks" , "CS"
s := fmt.Sprint(name, " is a " , dept, " Portal.\n" )
io.WriteString(os.Stdout, s)
}
|
Output:
GeeksforGeeks is a CS Portal.
Example 2:
package main
import (
"fmt"
"io"
"os"
)
func main() {
const num1, num2, num3 = 5, 10, 15
s := fmt.Sprint(num1, num2, num3)
io.WriteString(os.Stdout, s)
}
|
Output:
5 10 15
In the above code, it can be seen that the function Sprint() is not using any space still space can be seen in the output between the numbers because the function itself added the spaces because not a single string is used as the constant variable.
Example 3:
package main
import (
"fmt"
"io"
"os"
)
func main() {
const str1, str2, str3 = "a" , "b" , "c"
s := fmt.Sprint(str1, str2, str3)
io.WriteString(os.Stdout, s)
}
|
Output:
abc
In the above code, it can be seen that the function Sprint() is not using any space and also spaces can not be seen in the output in between two alphabets this is because strings are used in the constant variables.
Share your thoughts in the comments
Please Login to comment...