fmt
Turning numbers and booleans into text, aligning text, and building a string from a template.
import fmt
When you want tidy, readable output, the fmt package is what you reach for. With it you turn numbers into text, line text up in fixed-width columns, and build sentences from a template.
The templates are simple: every {} in the template is filled with the next element of the vector of values. Since the values are strings, convert numbers first with a function such as Int.
Functions
Int
func Int(i: i64): strimport fmt
func main:
println "[" + fmt.Int(-42) + "]"
println "[" + fmt.Uint(42 as u64) + "]"
println "[" + fmt.Float(3.25) + "]"
println "[" + fmt.FloatPrec(3.14159, 2) + "]"
println "[" + fmt.Bool(true) + "]"
println "[" + fmt.Hex(255 as u64) + "]"
endFloat
func Float(f: f64): strThe example for this item is shown with the ones above: fmt-Int.salam
Bool
func Bool(b: bool): str"true" or "false".The example for this item is shown with the ones above: fmt-Int.salam
PadLeft
func PadLeft(s: str, width: int): strwidth, adds spaces on its left until it reaches that width. The width counts characters, so it behaves correctly outside ASCII too. In a column of numbers this is what lines them up on the right.import fmt
func main:
println "[" + fmt.PadLeft("42", 6) + "]"
println "[" + fmt.PadRight("42", 6) + "]"
println "[" + fmt.Center("42", 6) + "]"
println "[" + fmt.PadLeft("salam", 10) + "]"
endPadRight
func PadRight(s: str, width: int): strPadLeft, but puts the spaces on the right of the text.The example for this item is shown with the ones above: fmt-PadLeft.salam
Center
func Center(s: str, width: int): strThe example for this item is shown with the ones above: fmt-PadLeft.salam
Sprintf
func Sprintf(tmpl: str, args: Vector<str>): str{} in turn from the args vector. If the values run out the remaining holes are left empty, and extra values are ignored.import fmt
func main:
mut values := Vector {} as Vector<str>
defer values.free()
values.push("Sara")
values.push(fmt.Int(19))
println fmt.Sprintf("{} scored {}.", values)
endFprintf
func Fprintf(f: File*, tmpl: str, args: Vector<str>): intSprintf, but writes the result straight into an open file and returns the number of bytes written.import fmt
import io
import os
func main:
mut values := Vector {} as Vector<str>
defer values.free()
values.push("25")
f := os.Open("temperature.txt", "wb")
fmt.Fprintf(f, "today it is {} degrees\n", values)
io.Close(f)
print io.ReadFile("temperature.txt")
endFloatPrec
func FloatPrec(f: f64, prec: int): strThe example for this item is shown with the ones above: fmt-Int.salam
Uint
func Uint(u: u64): stri64.The example for this item is shown with the ones above: fmt-Int.salam
Hex
func Hex(u: u64): str0x prefix.The example for this item is shown with the ones above: fmt-Int.salam