Output Functions in Go
Go provides three main functions to display text to the console:
- Print() – Outputs the text without adding a newline at the end.
- Println() – Outputs the text followed by a newline.
- Printf() – Formats and outputs the text using format specifiers (like %d, %s, etc.).
These functions are part of the fmt package.
The Print() Function:
- The Print() function outputs its arguments using their default formatting, without adding spaces or newlines automatically.
Example1:
package main
import ("fmt")
func main() {
var i, j string = "Hello", "World"
fmt.Print(i)
fmt.Print(j)
}
Output:
HelloWorld
Explanation:
- This program declares two string variables i and j, assigns them the values "Hello" and "World", and prints them without spaces using fmt.Print().
Example2:
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i + "\n")
fmt.Print(j + "\n")
}
Output:
Hello
World
Example3:
- You can also use a single Print() statement to print multiple variables, including newline characters.
package main
import ("fmt")
func main() {
var i, j string = "Hello", "World"
fmt.Print(i, "\n", j)
}
Output:
Hello
World
Example4:
- Adding a space between string arguments
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i, " ", j)
}
Output:
Hello World
Example5:
package main
import "fmt"
func main() {
i, j := 10, 20
fmt.Print(i, j)
}
Output:
10 20
Note: Print() inserts a space between arguments if neither of them is a string.
The Println() Function
- The Println() function works like Print(), but with two key differences:
- It automatically adds a space between the arguments and appends a newline character at the end.
- package main
Example:
import "fmt"
func main() {
message1 := "Hello"
message2 := "World"
fmt.Println(message1, message2)
}
Output:
Hello World
The Printf() Function in Go
The Printf() function is used to format and print data according to a specified format string. It allows you to control how values are displayed by using formatting verbs.
Common Formatting Verbs:
- %v – Prints the value of the variable
- %T – Prints the type of the variable
Example:
package main
import ("fmt")
func main() {
var i string = "Hello"
var j int = 15
fmt.Printf("i has value: %v and type: %T\n", i, i)
fmt.Printf("j has value: %v and type: %T", j, j)
}
Output:
i has value: Hello and type: string
j has value: 15 and type: int
- This example shows how Printf() can be used to print both the values and their types using format specifiers.