In Golang, several functions are available for printing text, and each serves specific use cases. Here's an explanation of the most commonly used printing functions:
Description:
Prints the provided arguments as plain text without adding a newline. It does not format the output.
Use Case:
For simple concatenated text or values where no specific formatting is required.
fmt.Print("Hello") // Output: Hello fmt.Print("World") // Output: HelloWorld fmt.Print(123, " GoLang") // Output: HelloWorld123 GoLang
Description:
Prints the provided arguments as plain text and appends a newline at the end.
Use Case:
For simple outputs where you want automatic line breaks after printing.
fmt.Println("Hello") // Output: Hello (with newline) fmt.Println("World") // Output: World (on a new line) fmt.Println(123, "GoLang") // Output: 123 GoLang (on a new line)
Description:
Formats and prints text according to a specified format string. Does not add a newline unless explicitly included in the format string.
Use Case:
For dynamic or formatted outputs (e.g., integers, floats, strings, etc.).
name := "Alice" age := 25 fmt.Printf("My name is %s and I am %d years old.", name, age) // Output: My name is Alice and I am 25 years old.
Verb | Description | Example |
---|---|---|
%s | String | fmt.Printf("%s", "Go") |
%d | Integer (base 10) | fmt.Printf("%d", 123) |
%f | Floating-point | fmt.Printf("%.2f", 3.14) |
%v | Default format for any value | fmt.Printf("%v", true) |
%T | Type of the variable | fmt.Printf("%T", name) |
% v | Struct with field names | fmt.Printf("% v", obj) |
Description:
Formats text like fmt.Printf, but instead of printing to the console, it returns the formatted string.
Use Case:
For preparing strings for later use (e.g., logging, building responses).
formatted := fmt.Sprintf("Hello, %s!", "Alice") fmt.Println(formatted) // Output: Hello, Alice!
The above is the detailed content of PostGolang Print Functions. For more information, please follow other related articles on the PHP Chinese website!