What are the common functions in the fmt package?

Common Functions in the fmt Package

The fmt package in Go provides a set of functions for formatting and printing output. Here are some of the most commonly used functions in the fmt package:

Print and Println Functions

  • fmt.Print(): Prints the arguments to the standard output, without a trailing newline character.
  • fmt.Println(): Prints the arguments to the standard output, followed by a newline character.

Example:

fmt.Print("Hello, ")
fmt.Println("world!")
// Output: Hello, world!

Printf Function

  • fmt.Printf(): Prints the output according to a format specifier, similar to the printf() function in C.

Example:

name := "Alice"
age := 25
fmt.Printf("Name: %s, Age: %d", name, age)
// Output: Name: Alice, Age: 25

Sprintf Function

  • fmt.Sprintf(): Formats the arguments according to a format specifier and returns the resulting string.

Example:

name := "Alice"
age := 25
info := fmt.Sprintf("Name: %s, Age: %d", name, age)
fmt.Println(info)
// Output: Name: Alice, Age: 25

Scan Functions

  • fmt.Scan(): Reads input from the standard input, splitting the input by whitespace and assigning the values to the specified variables.
  • fmt.Scanln(): Reads input from the standard input, stopping at a newline character.
  • fmt.Scanf(): Reads input from the standard input, parsing the input according to a format specifier.

Example:

var name string
var age int
fmt.Print("Enter your name and age: ")
fmt.Scanln(&name, &age)
fmt.Printf("Name: %s, Age: %d", name, age)

Fprint Functions

  • fmt.Fprint(): Prints the arguments to the specified io.Writer interface, without a trailing newline character.
  • fmt.Fprintln(): Prints the arguments to the specified io.Writer interface, followed by a newline character.
  • fmt.Fprintf(): Prints the output to the specified io.Writer interface, according to a format specifier.

Example:

file, err := os.Create("output.txt")
if err != nil {
    fmt.Println("Error creating file:", err)
    return
}
defer file.Close()

fmt.Fprintf(file, "Hello, %s!", "world")

Error Handling Functions

  • fmt.Errorf(): Formats the arguments according to a format specifier and returns an error.

Example:

err := fmt.Errorf("invalid input: %d", -1)
fmt.Println(err)
// Output: invalid input: -1

These are some of the most common functions in the fmt package. The package provides a wide range of functionality for formatting and printing output, as well as reading input, making it a crucial part of many Go programs.

0 Comments

no data
Be the first to share your comment!