String formatting examples using fmt.printf in Golang 1.20
In this video we are going to generate source code for the GoLang Program, string formatting examples in printf using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import "fmt"
func main() {
// Example 1: Basic string formatting
name := "John"
fmt.Printf("Hello, %s!\n", name)
// Example 2: Formatting integers
age := 30
fmt.Printf("You are %d years old.\n", age)
// Example 3: Formatting floats
temperature := 23.5
fmt.Printf("The temperature is %.2f degrees Celsius.\n", temperature)
// Example 4: Formatting booleans
isRaining := true
fmt.Printf("Is it raining? %t\n", isRaining)
// Example 5: Formatting characters
firstInitial := 'J'
fmt.Printf("First initial: %c\n", firstInitial)
// Example 6: Formatting Unicode code points
heart := '❤'
fmt.Printf("Unicode code point: U+%04X\n", heart)
// Example 7: Formatting binary, octal, and hexadecimal integers
number := 42
fmt.Printf("Binary: %b, Octal: %o, Hexadecimal: %x\n", number, number, number)
// Example 8: Formatting pointers
x := 10
fmt.Printf("Memory address of x: %p\n", &x)
// Example 9: Formatting multiple values
firstName := "John"
lastName := "Doe"
fmt.Printf("Full name: %s %s\n", firstName, lastName)
// Example 10: Using flags to modify formatting
balance := 1234.5678
fmt.Printf("Balance: %e\n", balance)
fmt.Printf("Balance (fixed-point notation): %.2f\n", balance)
fmt.Printf("Balance (scientific notation): %.2E\n", balance)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
This program demonstrates 10 different examples of string formatting in the printf function:
Basic string formatting using %s
Formatting integers using %d
Formatting floats using %f
Formatting booleans using %t
Formatting characters using %c
Formatting Unicode code points using %X
Formatting binary, octal, and hexadecimal integers using %b, %o, and %x
Formatting pointers using %p
Formatting multiple values using multiple format specifiers
Using flags to modify formatting, such as scientific notation using %E or %e, and fixed-point notation using %.2f.
When you run this program, you should see output like the following:
Hello, John!
You are 30 years old.
The temperature is 23.50 degrees Celsius.
Is it raining? true
First initial: J
Unicode code point: U+2764
Binary: 101010, Octal: 52, Hexadecimal: 2a
Memory address of x: 0xc0000180d0
Full name: John Doe
Balance: 1.234568e+03
Balance (fixed-point notation): 1234.57
Balance (scientific notation): 1.23E+03
This program demonstrates how to use the printf function to format strings in a variety of ways in Go.
#go #goprogramming #golang #golangtutorial #golanguage