Go Package fmt: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 10: Line 10:
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
i := 7
i := 7
s := fmt.Sprintf("%06d", i) # will produce "000007" (five zeroes)
s := fmt.Sprintf("%06d", i) // will produce "000007" (five zeroes)
</syntaxhighlight>
</syntaxhighlight>



Revision as of 19:43, 20 December 2023

External

Internal

Formatting

Leading Zero Padding for Integers

i := 7
s := fmt.Sprintf("%06d", i) // will produce "000007" (five zeroes)

Leading Space Padding for Integer

i := 7
s := fmt.Sprintf("%6d", i) # will produce "     7" (five spaces)

Functions

Sprintf()

Format a string and returns it as a result:

message := fmt.Sprintf("Hi, %v. Welcome!", name)

For more details on the format string, see:

Printf() Format String

Printf(), Println()

Printing to stdout and stderr

Scanf(), Scanln()

Handling stdin in Go

Errorf()

Error Handling | Wrapping Errors

Interfaces

fmt.Stringer

type Stringer interface {
  String() string
}

Stringer is implemented by any type that has a String() method, which defines the "native" format for that value. The String() method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print. For a usage example, see:

The Equivalent of Java toString() in Go