in this post, we’ll show you how to format strings in Golang. Golang has a large number of string formatting options. The fmt is a golang package that can be used to format a string. This package has inbuilt find functions that implement formatted I/O.
To format strings in Go, we use the following functions:
The fmt package enables you to convert strings, numbers, and even objects to a particular string format. All of the formatting methods are parts of this package.
The fmt package provides a wide variety of string formatting functionalities. The formating method will format the string according to the specified format specifiers. Let’s look at a few popular string formatting examples in GoLang.
The fmt.Printf() method prints a formatted string to the console. The %s expects a string value and the %d an integer value.
Example:
package main
import (
"fmt"
)
func main() {
emp_name := "Rachel"
age := 17
salary := 123
fmt.Printf("My name is %s, and I am %d years old. My annual wage is %d dollars\n", emp_name, age, salary)
}
Output :
My name is Rachel, and I am 17 years old. My annual wage is 123 dollars
The fmt.Sprintf function formats a string into a variable.
Example:
package main
import (
"fmt"
)
func main() {
emp_name := "Rachel"
age := 17
salary := 123
formatted_str := fmt.Sprintf("My name is %s, and I am %d years old. My annual wage is %d dollars\n", emp_name, age, salary)
fmt.Println(formatted_str)
}
Output :
My name is Rachel, and I am 17 years old. My annual wage is 123 dollars
The Go language’s fmt.Fscanf() method scans the supplied text, reads from r, and then stores the space-separated values into subsequent arguments according to the format.
Syntax:
func Fscanf(r io.Reader, format string, a …interface{}) (n int, err error)
It returns the number of items successfully parsed. The above function accepts three parameters:
Example:
package main
import (
"fmt"
"os"
"strings"
)
func main() {
var (
emp_name string
age int
salary int
)
r := strings.NewReader("Rachel 23 123")
emp, err := fmt.Fscanf(r, "%s %d %d", &emp_name, &age, &salary)
if err != nil {
fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
}
fmt.Println(emp_name, age, salary)
fmt.Println(emp)
}
Output :
Rachel 23 123 3
This golang tutorial help to understand the go string package. This tutorial applies some manipulation…
This tutorial help to implement an in-memory cache system into golang application. I am creating…
in this tutorial, we'll cover learn how to string replace in golang.The strings.Replace() function is…
dig Library is a mobile library. Provide injection of dependencies (dependency injection) The toolbox should…
To convert an int to a string, Golang has a built-in package and methods. To…
in this post, We'll learn here about converting an int value to string in golang.…