Formatted print
Printing is handled by a series of macros defined in
core::fmt some of which are:
format!: write formatted text toByteArrayprint!: same asformat!but the text is printed to the console (stdout).println!: same asprint!but a newline is appended.
All parse text in the same fashion. As a plus, Cairo checks formatting correctness at compile time.
struct Structure {
inner: i32,
}
fn main() {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Positional arguments can be used. Specifying an integer inside `{}`
// determines which additional argument will be replaced. Arguments start
// at 0 immediately after the format string.
let alice: ByteArray = "Alice";
let bob: ByteArray = "Bob";
println!("{0}, this is {1}. {1}, this is {0}", alice, bob);
// Different formatting can be invoked by specifying the format character
// after a `:`.
println!("Base 10: {}", 69420); // 69420
println!("Base 16 (hexadecimal): {:x}", 69420); // 10f2c
// Cairo even checks to make sure the correct number of arguments are used.
let bond: ByteArray = "Bond";
println!("My name is {0}, {1} {0}", bond);
// FIXME ^ Add the missing argument: "James"
// Only types that implement fmt::Display can be formatted with `{}`. User-
// defined types do not implement fmt::Display by default.
// This will not compile because `Structure` does not implement
// fmt::Display.
// println!("This struct `{}` won't print...", Structure(3));
// TODO ^ Try uncommenting this line
}
core::fmt contains many traits which govern the display
of text. The base form of two important ones are listed below:
fmt::Debug: Uses the{:?}marker. Format text for debugging purposes.fmt::Display: Uses the{}marker. Format text in a more elegant, user friendly fashion.
Here, we used fmt::Display because the std library provides implementations
for these types. To print text for custom types, more steps are required.
Activities
- Fix the issue in the above code (see FIXME) so that it runs without error.
- Try uncommenting the line that attempts to format the
Structurestruct (see TODO)