Standard library · Basics

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.

Coming from printf or Go, watch for these:

  • There are no verbs such as %d or {:.2}. A hole is always a bare {}; widths and decimals are set by formatting the value first with PadLeft or FloatPrec.
  • A literal {} cannot be written in a template, because there is no escape for it.
  • Hex and Uint take a u64, so an int needs a cast: fmt.Hex(n as u64).

Printing a table

A table in plain text is a row of padded cells. Text columns read best aligned to the left with PadRight, and number columns aligned to the right with PadLeft, so the digits of each place line up. A small helper that builds one row keeps every line of the table the same shape, header included.

fmt-guide-receipt.salam
import fmt

struct Line:
    pub name: str = ""
    pub qty: int = 0
    pub price: f64 = 0.0
end

func row(a: str, b: str, c: str): str:
    ret fmt.PadRight(a, 12) + fmt.PadLeft(b, 5) + fmt.PadLeft(c, 10)
end

func main:
    items := [Line { name = "Coffee", qty = 2, price = 3.5 }, Line { name = "Croissant", qty = 3, price = 2.25 }, Line { name = "Water", qty = 1, price = 1.0 }]
    println "|" + fmt.Center("RECEIPT", 25) + "|"
    println row("item", "qty", "amount")
    mut total := 0.0
    each it in items:
        amount := it.price * it.qty
        total += amount
        println row(it.name, fmt.Int(it.qty), fmt.FloatPrec(amount, 2))
    end
    println row("total", "", fmt.FloatPrec(total, 2))
end
Output| RECEIPT | item qty amount Coffee 2 7.00 Croissant 3 6.75 Water 1 1.00 total 14.75

Money is printed with FloatPrec and two places, so 7 shows as 7.00 and every amount has the same width. The widths count characters, not bytes, so the same code lines up Persian or Arabic names too. A value longer than its column is never cut, it only pushes the rest of the row to the right; pick widths that fit your longest value.

If the names are in Persian or Arabic and you look at the table in a terminal, the columns may appear in a different order, because how mixed right-to-left text and numbers are shown depends on the Unicode bidirectional algorithm. The strings themselves are correct; for exact display on the web, use an HTML table.

Filling a message template

Sprintf fills each {} with the next string from a vector. Keeping the sentence in one template, instead of a long chain of +, makes it easy to read and easy to change later, or to swap for a translated template. Numbers and booleans go in through Int, Float or Bool first, because every value is a string.

fmt-guide-messages.salam
import fmt

struct Order:
    pub customer: str = ""
    pub id: int = 0
    pub paid: bool = false
end

func notice(o: Order): str:
    mut args := Vector {} as Vector<str>
    defer args.Free()
    args.Push(o.customer)
    args.Push(fmt.Int(o.id))
    args.Push(o.paid ? "paid" : "waiting for payment")
    ret fmt.Sprintf("Dear {}, order #{} is {}.", args)
end

func main:
    println notice(Order { customer = "Nima", id = 1042, paid = true })
    println notice(Order { customer = "Leila", id = 1043 })
end
OutputDear Nima, order #1042 is paid. Dear Leila, order #1043 is waiting for payment.

The vector of values belongs to you, so free it when the message is built. When the result should go to a file instead of a string, Fprintf takes the same template and values and writes them to an open File*.

Hexadecimal output

Hex writes a number in base sixteen with lower case letters and no 0x, and it does not add leading zeros. Formats with a fixed width, such as a CSS color where each channel is exactly two digits, need that zero added by hand.

fmt-guide-colors.salam
import fmt

func two_hex(n: int): str:
    h := fmt.Hex(n as u64)
    if h.Len() < 2:
        ret "0" + h
    end
    ret h
end

func css_color(r: int, g: int, b: int): str:
    ret "#" + two_hex(r) + two_hex(g) + two_hex(b)
end

func main:
    println css_color(255, 165, 0)
    println css_color(0, 128, 128)
    println css_color(9, 9, 9)
    mut shade := 0
    until shade <= 255:
        println fmt.PadLeft(fmt.Int(shade), 3), css_color(shade, shade, shade)
        shade += 85
    end
end
Output#ffa500 #008080 #090909 0 #000000 85 #555555 170 #aaaaaa 255 #ffffff

PadLeft always pads with spaces, which is right for the shade column on the left but not for hex digits. For anything bigger than one byte, compare the length with the width you need and add as many zeros as are missing.

Which function for which job

JobFunction
A whole number as textInt, or Uint for u64
A decimal number, shortest formFloat
A decimal with a fixed number of placesFloatPrec
Align text in a columnPadRight (left aligned), PadLeft (right aligned), Center
A sentence with values in itSprintf, or Fprintf into a file
Base sixteenHex

For parsing text back into numbers, see conv. For templates with names, loops and conditions, such as an HTML page or an email, use template.

Functions

Int

func Int(i: i64): str
Turns a whole number into text, with a minus sign where one is needed.
fmt-Int.salam
import 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) + "]"
end
Output[-42] [42] [3.25] [3.14] [true] [ff]

Float

func Float(f: f64): str
Turns a decimal number into the shortest text that reads back as the same number: 1.0 becomes 1, 0.1 stays 0.1 and 1.0 / 3.0 becomes 0.3333333333333333. Very large or very small numbers use an exponent, such as 1e+21. Use FloatPrec when the number of places must be fixed.

The example for this item is shown with the ones above: fmt-Int.salam

Bool

func Bool(b: bool): str
Turns a boolean into "true" or "false".

The example for this item is shown with the ones above: fmt-Int.salam

PadLeft

func PadLeft(s: str, width: int): str
If the text is shorter than width, 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.
fmt-PadLeft.salam
import fmt

func main:
    println "[" + fmt.PadLeft("42", 6) + "]"
    println "[" + fmt.PadRight("42", 6) + "]"
    println "[" + fmt.Center("42", 6) + "]"
    println "[" + fmt.PadLeft("salam", 10) + "]"
end
Output[ 42] [42 ] [ 42 ] [ salam]

PadRight

func PadRight(s: str, width: int): str
Like PadLeft, 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): str
Places the text in the middle of the given width. When the padding does not divide evenly, the extra space goes on the right.

The example for this item is shown with the ones above: fmt-PadLeft.salam

Sprintf

func Sprintf(tmpl: str, args: Vector<str>): str
Takes the template and fills each {} in turn from the args vector. If the values run out the remaining holes are left empty, and extra values are ignored.
fmt-Sprintf.salam
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)
end
OutputSara scored 19.

Fprintf

func Fprintf(f: File*, tmpl: str, args: Vector<str>): int
Like Sprintf, but writes the result straight into an open file and returns the number of bytes written.
fmt-Fprintf.salam
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")
end
Outputtoday it is 25 degrees

FloatPrec

func FloatPrec(f: f64, prec: int): str
Turns a decimal number into text with the number of decimal places you ask for. Halves round away from zero, as on paper: 2.675 with two places is 2.68 and -1.5 with none is -2.

The example for this item is shown with the ones above: fmt-Int.salam

Uint

func Uint(u: u64): str
Turns an unsigned 64-bit number into text, for numbers too large to fit in an i64.

The example for this item is shown with the ones above: fmt-Int.salam

Hex

func Hex(u: u64): str
Writes the number in base sixteen in lower case, with no 0x prefix and no leading zeros. It takes a u64, so cast an int with as u64.

The example for this item is shown with the ones above: fmt-Int.salam