Home > Backend Development > Golang > PostGolang Print Functions

PostGolang Print Functions

Linda Hamilton
Release: 2024-12-31 11:21:13
Original
521 people have browsed it

PostGolang Print Functions

series: Golang

Printing Functions in Golang

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:

1. fmt.Print

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
Copy after login

2. fmt.Println

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)
Copy after login

3. fmt.Printf

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.
Copy after login

Common Formatting Verbs:

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)

4. fmt.Sprintf

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!
Copy after login

The above is the detailed content of PostGolang Print Functions. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template