Go Output Functions

Output functions are used to display data on the console or in a file. There are several built-in output functions in Golang, including fmt.Println, fmt.Printf, and fmt.Sprintf.

Here are some examples of how to use these output functions:

fmt.Println

The fmt.Println function is used to print one or more values to the console, followed by a newline character. Here’s an example:

package main

import "fmt"

func main() {
    name := "John"
    age := 42
    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
}

In this example, we declare a variable called name and assign it a value of “John”, and a variable called age and assign it a value of 42. We then use the fmt.Println function to print the values of these variables to the console.

When you run this program, you should see the following output:

Name: John
Age: 42

fmt.Printf

The fmt.Printf function is used to format and print values to the console. It allows you to specify a format string that defines how the values should be printed. Here’s an example:

package main

import "fmt"

func main() {
    name := "John"
    age := 42
    fmt.Printf("Name: %s\n", name)
    fmt.Printf("Age: %d\n", age)
}

In this example, we use the fmt.Printf function to print the values of the name and age variables using a format string. The %s and %d placeholders in the format string are replaced with the values of the name and age variables, respectively.

When you run this program, you should see the same output as in the previous example.

fmt.Sprintf

The fmt.Sprintf function is used to format a string and return the result as a new string. Here’s an example:

package main

import "fmt"

func main() {
    name := "John"
    age := 42
    output := fmt.Sprintf("Name: %s\nAge: %d", name, age)
    fmt.Println(output)
}

In this example, we use the fmt.Sprintf function to format a string that contains the values of the name and age variables. We then print the formatted string to the console using the fmt.Println function.

When you run this program, you should see the same output as in the previous examples.

Follow us on social media
Follow Author