Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Format a message without printing in Go (Golang)

Posted on September 21, 2020September 21, 2020 by admin

Table of Contents

  • Overview
  • Example

Overview

Sprintf function of fmt package can be used to format the string without printing it.  It is similar to Printf function with the only difference between the two being

  • Printf formats and print the message
  • Sprintf only formats the message.

Below is the syntax of the Sprintf function

func Sprintf(format string, a ...interface{}) string

The Sprintf function formats the string according to format specifier and returns the resultant string

Example

Let’s see a program for this

package main

import "fmt"

func main() {
    formattedMessage := fmt.Sprintf("Name is: %s. Age is: %d", "John", 21)
    fmt.Println(formattedMessage)
}

Output

Name is: John. Age is: 21

In the above program fmt.Sprintf correctly formats the message while fmt.Println is used to print the formatted message

  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme