Menu Close

Go – How to format string without printing in go

In this tutorial, We are going to learn about how to format string without printing in go. Go provides very simple way to format a string without printing the string. We can do it by using Sprintf() function of fmt package in go.

Syntax:

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

Sprintf() function in fmt package formats string according to a format specifier and returns the resulting string.

Example:

1:) name = "john"
City = "KCP"

s := fmt.Sprintf("%s is from %s\n", name, city)

Output: john is from KCP

2:) name = "BOB"
age = 20

s := fmt.Sprintf("%s is %d\n", name, age)

Output: BOB is 20

Example with code:

package main

import (

  "fmt"

)

func main() {

  name := "john"

  city := "KCP"

  str := fmt.Sprintf("%s is from %s\n", name, city)

  fmt.Println(str)


  name = "BOB"

  age := 20

  str = fmt.Sprintf("%s is %d\n", name, age)

  fmt.Println(str)
}

Output:

john is from KCP

BOB is 20

To learn more about golang, You can refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

 https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang, Miscellaneous

Leave a Reply

Your email address will not be published. Required fields are marked *