Documentation
¶
Overview ¶
Package format appends values to byte buffers using Python-like replacement fields and format specifications.
Index ¶
- func AppendBytes(dst []byte, formatSpec string, b []byte) []byte
- func AppendDuration(dst []byte, formatSpec string, value time.Duration) []byte
- func AppendFloat(dst []byte, formatSpec string, v float64) []byte
- func AppendFloat32(dst []byte, formatSpec string, v float32) []byte
- func AppendInt(dst []byte, formatSpec string, v int64) []byte
- func AppendSigFixed(dst []byte, value float64) []byte
- func AppendSigFixed32(dst []byte, value float32, sig int) []byte
- func AppendSigFixed64(dst []byte, value float64, sig int) []byte
- func AppendString(dst []byte, formatSpec string, s string) []byte
- func AppendUint(dst []byte, formatSpec string, v uint64) []byte
- func Format(dst []byte, template string, a ...any) []byte
Examples ¶
- Format
- Format (Binary)
- Format (Booleans)
- Format (ByteSlice)
- Format (EscapedBraces)
- Format (FloatGrouping)
- Format (FloatPrecision)
- Format (Hexadecimal)
- Format (MixedTypes)
- Format (MultipleArguments)
- Format (ReuseBuffer)
- Format (SignDisplay)
- Format (StringPadding)
- Format (ThousandsSeparator)
- Format (ZeroPadding)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendBytes ¶
AppendBytes formats b according to formatSpec and appends the result to dst. An empty spec appends b as text, while other string layout specs apply the same alignment, width and precision rules as AppendString. The x, X and q presentations accept an optional string fill, alignment and width prefix. The standalone v and # specs produce a decimal list and Go syntax.
b must not refer to dst's backing array, even when dst has zero length. Calls such as AppendBytes(b[:0], formatSpec, b) are unsupported.
func AppendDuration ¶
AppendDuration appends the same textual representation as time.Duration.String and applies the string fill, alignment, width and precision rules.
func AppendFloat ¶
AppendFloat formats v according to formatSpec and appends the result to dst, returning the extended buffer. An unparsable formatSpec yields a "%!(BADSPEC:...)" marker followed by v in 'g' with the smallest number of digits that round-trips.
func AppendFloat32 ¶
AppendFloat32 is AppendFloat for float32 values: the result carries only the digits a float32 actually distinguishes, rather than the exact decimal expansion of its binary value.
func AppendInt ¶
AppendInt formats v according to formatSpec and appends the result to dst, returning the extended buffer. An unparsable formatSpec yields a "%!(BADSPEC:...)" marker followed by v in plain base 10. With the c presentation, a value that is not a valid Unicode code point falls back to plain base 10 without applying the other format options.
func AppendSigFixed ¶
AppendSigFixed is AppendSigFixed64 with the default precision of 13, which keeps values down to 1e-13.
func AppendSigFixed32 ¶
AppendSigFixed32 is AppendSigFixed64 for float32 values. The result never carries more than 9 significant digits, which is all a float32 distinguishes.
func AppendSigFixed64 ¶
AppendSigFixed64 appends value in fixed-point notation, never an exponent, with trailing zeros trimmed. At or above 1, sig limits significant digits, rounding within the integer part when necessary. Below 1, sig counts fractional digits, so a value too small for them formats as "0". sig must be between 1 and 15; it panics otherwise.
func AppendString ¶
AppendString formats s according to formatSpec and appends the result to dst, returning the extended buffer.
The spec accepts an optional fill and alignment, a width and a precision; precision truncates s to that many runes. Width and truncation are counted in runes, not bytes. An unparsable formatSpec yields a "%!(BADSPEC:...)" marker followed by s unformatted.
func AppendUint ¶
AppendUint formats v according to formatSpec and appends the result to dst, returning the extended buffer. An unparsable formatSpec yields a "%!(BADSPEC:...)" marker followed by v in plain base 10.
Unlike AppendInt, values above math.MaxInt64 keep their full magnitude, so this is the correct entry point for uint, uint64 and uintptr. With the c presentation, a value that is not a valid Unicode code point falls back to plain base 10 without applying the other format options.
func Format ¶
Format formats a template string with the provided arguments and appends the result to dst. It returns the extended buffer.
Example:
buf := make([]byte, 0, 128)
buf = format.Format(buf, "Hello {}, you are {} years old!", "Alice", 30)
// buf now contains: "Hello Alice, you are 30 years old!"
// Reuse the buffer
buf = format.Format(buf[:0], "Price: ${:.2f}", 19.99)
// buf now contains: "Price: $19.99"
// Various format specifiers
buf = format.Format(nil, "{:#08x} {:,d}", 255, 1000000)
// returns: "0x0000ff 1,000,000"
Template syntax:
- {} - empty placeholder
- {format} or {:format} - placeholder with format spec (: is optional and will be stripped)
- {{ - literal {
- }} - literal }
Supported types:
- int, int8, int16, int32, int64
- uint, uint8, uint16, uint32, uint64, uintptr
- float32, float64
- string; []byte and byte arrays with the x, X, q, v and # presentations. A spec naming none gives text for []byte but hex for an array, which is a hash or key far more often than it is text.
- bool
- time.Duration
- error and fmt.Stringer, formatted by the string rules
A defined type is formatted by its underlying kind, so `type ID uint64` obeys every uint64 spec. An Error or String method takes precedence over the kind. The # presentation names the defined type, the way %#v does.
Types with no supported kind are formatted using fmt.Sprintf("%v", value).
With enough capacity in dst, common supported values and format specs usually need no internal allocations. Passing runtime values through `...any` may still allocate at the call site, depending on the compiler and call shape. Unsupported values use fmt.Sprintf, Error and String methods control their own allocation behavior, and unusually large float output may need a larger temporary buffer.
A []byte argument must not refer to dst's backing array, even when dst has zero length. Calls such as Format(b[:0], "{x}", b) are unsupported.
Use the AppendInt/AppendUint/AppendFloat/AppendDuration/AppendString/ AppendBytes family where the extra allocation matters; those take concrete types and avoid `any` boxing.
Example ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
// Basic integer formatting
result := format.Format(nil, "Answer: {}", 42)
fmt.Println(string(result))
}
Output: Answer: 42
Example (Binary) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Binary: {:b}, With prefix: {:#b}", 5, 5)
fmt.Println(string(result))
}
Output: Binary: 101, With prefix: 0b101
Example (Booleans) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Is active: {}, Is admin: {}", true, false)
fmt.Println(string(result))
}
Output: Is active: true, Is admin: false
Example (ByteSlice) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
data := []byte("hello")
result := format.Format(nil, "Data: {}", data)
fmt.Println(string(result))
}
Output: Data: hello
Example (EscapedBraces) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Set: {{ {} }}", 42)
fmt.Println(string(result))
}
Output: Set: { 42 }
Example (FloatGrouping) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Price: ${:,.2f}", 12345.67)
fmt.Println(string(result))
}
Output: Price: $12,345.67
Example (FloatPrecision) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Pi is approximately {:.2f}", 3.14159)
fmt.Println(string(result))
}
Output: Pi is approximately 3.14
Example (Hexadecimal) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Color: {:#08x}", 255)
fmt.Println(string(result))
}
Output: Color: 0x0000ff
Example (MixedTypes) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Name: {}, Age: {}, Height: {:.2f}m", "Alice", 30, 1.65)
fmt.Println(string(result))
}
Output: Name: Alice, Age: 30, Height: 1.65m
Example (MultipleArguments) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "{} + {} = {}", 2, 3, 5)
fmt.Println(string(result))
}
Output: 2 + 3 = 5
Example (ReuseBuffer) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
buf := make([]byte, 0, 128)
// First use
buf = format.Format(buf, "Line 1: {}", 100)
fmt.Println(string(buf))
// Reuse buffer
buf = format.Format(buf[:0], "Line 2: {}", 200)
fmt.Println(string(buf))
}
Output: Line 1: 100 Line 2: 200
Example (SignDisplay) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "{:+d} {:+d}", 42, -42)
fmt.Println(string(result))
}
Output: +42 -42
Example (StringPadding) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "[{:<10}] [{:>10}] [{:^10}]", "left", "right", "center")
fmt.Println(string(result))
}
Output: [left ] [ right] [ center ]
Example (ThousandsSeparator) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "Population: {:,d}", 1234567)
fmt.Println(string(result))
}
Output: Population: 1,234,567
Example (ZeroPadding) ¶
package main
import (
"fmt"
"github.com/gavriva/format"
)
func main() {
result := format.Format(nil, "ID: {:05d}", 42)
fmt.Println(string(result))
}
Output: ID: 00042
Types ¶
This section is empty.