Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Display

print and strings.Format know how to show numbers, strings and booleans. To make one of your own types printable, give it a cast to ustring: an operator cast that returns its text form.

#import "std/strings"

'' A type that can turn itself into text declares a cast to ustring.
type Point
    as float64 x, y
    declare operator cast( ) as ustring
end type

operator Point.cast( ) as ustring
    return strings.Format( "({}, {})", x, y )
end operator

dim p as Point = ( 1.5, -2 )

'' Every place that wants text now accepts a Point.
print p
print "p is " & p
print strings.Format( "p is {} and {:>14}", p, p )

Output

(1.5, -2)
p is (1.5, -2)
p is (1.5, -2) and      (1.5, -2)

Once the cast exists, a Point is accepted wherever text is expected: by print, by the & concatenation operator, and by strings.Format, where the format spec — here {:>14} — applies to the text the cast produced.

Types and operators are covered properly in Custom Types and Objects; this page only shows the hook that makes a value displayable.

Activities

  1. Add a z field to Point and include it in the text.
  2. Write a Money type holding a number of cents that prints as $12.34.