🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The fmt.Sprintf function in Golang is part of the fmt package and is used to create formatted strings using format specifiers. Unlike fmt.Printf, which prints formatted strings directly to the console, fmt.Sprintf returns the formatted string, allowing you to store it in a variable or use it in further processing.
Table of Contents
- Introduction
SprintfFunction Syntax- Examples
- Basic Usage
- Formatting Numbers and Strings
- Complex Formatting
- Real-World Use Case
- Conclusion
Introduction
The fmt.Sprintf function is useful when you need to create strings with specific formatting. By using format specifiers, you can control how different data types are represented in the resulting string. This is particularly helpful for creating detailed messages, constructing SQL queries, or formatting data for APIs.
Sprintf Function Syntax
The syntax for the fmt.Sprintf function is as follows:
func Sprintf(format string, a ...interface{}) string
Parameters:
format: A string containing format specifiers that define how the arguments should be formatted.a: The data to be formatted and inserted into the format string.
Returns:
- A string that contains the formatted output.
Common Format Specifiers:
%s: String%d: Integer (base 10)%f: Floating-point number%t: Boolean%v: Default format for the type%T: Type of the value%%: Literal percent sign
Examples
Basic Usage
This example demonstrates how to use the fmt.Sprintf function to create a formatted string with text and numbers.
Example
package main
import (
"fmt"
)
func main() {
name := "Alice"
age := 30
// Use fmt.Sprintf to format a string with placeholders
result := fmt.Sprintf("Name: %s, Age: %d", name, age)
// Print the formatted string
fmt.Println(result)
}
Output:
Name: Alice, Age: 30
Formatting Numbers and Strings
You can use fmt.Sprintf to format numbers with specific precision and to align text.
Example
package main
import (
"fmt"
)
func main() {
price := 123.456
quantity := 5
// Format floating-point numbers with two decimal places
priceStr := fmt.Sprintf("Price: $%.2f", price)
// Format numbers with leading zeros
quantityStr := fmt.Sprintf("Quantity: %03d", quantity)
// Print the formatted strings
fmt.Println(priceStr)
fmt.Println(quantityStr)
}
Output:
Price: $123.46
Quantity: 005
Complex Formatting
You can use fmt.Sprintf to create complex formatted strings with multiple variables.
Example
package main
import (
"fmt"
)
func main() {
product := "Laptop"
price := 999.99
inStock := true
// Use fmt.Sprintf to build a detailed string
details := fmt.Sprintf("Product: %s\nPrice: $%.2f\nIn Stock: %t", product, price, inStock)
// Print the formatted string
fmt.Println(details)
}
Output:
Product: Laptop
Price: $999.99
In Stock: true
Real-World Use Case
Constructing SQL Queries
In real-world applications, fmt.Sprintf can be used to construct SQL queries dynamically by embedding values into query templates.
Example
package main
import (
"fmt"
)
func main() {
table := "users"
condition := "age > 18"
// Construct an SQL query using fmt.Sprintf
query := fmt.Sprintf("SELECT * FROM %s WHERE %s;", table, condition)
// Print the SQL query
fmt.Println(query)
}
Output:
SELECT * FROM users WHERE age > 18;
Conclusion
The fmt.Sprintf function is a versatile way to create formatted strings in Go. It provides precise control over string formatting, making it ideal for generating dynamic messages, formatting numerical data, and constructing complex strings for various applications. By using fmt.Sprintf, you can enhance the readability and maintainability of your Go code when handling string manipulation.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment