×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang fmt.Printf() Function with Examples

Golang | fmt.Printf() Function: Here, we are going to learn about the Printf() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 08, 2021

fmt.Printf()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Printf() function is an inbuilt function of the fmt package which is used to format according to a format specifier and writes to standard output.

It accepts two parameters (format string, a ...interface{}) and returns the number of total bytes written and an error if occurred during the write operation.

Syntax:

func Printf(format string, a ...interface{}) (n int, err error)

Parameter(s):

  • format : String format with the format verbs.
  • a : A custom type that is used to specify a set of one or more method signatures, here we can provide a set of the variables, constants, functions, etc.

Return Value:

The return type of the fmt.Printf() function is (n int, err error), it returns the number of total bytes written and an error if occurred during the write operation.

Example 1:

// Golang program to demonstrate the
// example of fmt.Printf() function

package main

import (
	"fmt"
)

func main() {
	// Printing simple text
	n, err := fmt.Printf("Hello, world!")

	// Prints newline
	fmt.Println()

	// fmt.Print() returns:
	// n - Number of printed characters
	// err - Error (if any)
	fmt.Println(n, "Characters printed.")
	fmt.Println("Error: ", err)
}

Output:

Hello, world!
13 Characters printed.
Error:  <nil>

Example 2:

// Golang program to demonstrate the
// example of fmt.Printf() function

package main

import (
	"fmt"
)

func main() {
	// Print text with new line
	fmt.Printf("Hello World\n")
	fmt.Printf("Hi, there...\n")

	// Printing text, values together
	fmt.Printf("Name: %s, Age: %d\n", "Alex", 21)

	// Printing variable values

	// Declaring & assigning variables
	var (
		name string
		age  int
		perc float32
	)

	name = "Alex"
	age = 21
	perc = 87.5

	// Printing
	fmt.Printf("Name: %s, Age: %d, Perc: %.2f\n", name, age, perc)
}

Output:

Hello World
Hi, there...
Name: Alex, Age: 21
Name: Alex, Age: 21, Perc: 87.50

Example 3:

// Golang program to demonstrate the
// example of fmt.Printf() function

package main

import (
	"fmt"
)

func main() {
	name := "Dev"
	age := 21
	city := "New York"

	// Printing using fmt.Printf()
	fmt.Printf("Hey I'm %s, %d years old.\n", name, age)
	fmt.Printf("I live in %s\n", city)
}

Output:

Hey I'm Dev, 21 years old.
I live in New York

Golang fmt Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.