Home
Rust
format, concat Macro Examples
Updated May 17, 2024
Dot Net Perls
Format. How can we copy a formatted string containing other values like integers and arrays into a byte vector? In Rust this can be done with the format and concat macros.
While println can write formatted data to the console, we sometimes want to store this output in a String or byte vector. We can use format to create the string, and then copy it.
println
Example. This Rust program creates some strings containing formatted data. It then copies these strings to a byte vector and prints the vector the console.
Part 1 We use the "format!" macro here. The integer 10 and the array (with 3 values) is inserted into the string literal.
Part 2 If we have only constant values, we can use the concat macro. This creates a string containing the specified parts.
Part 3 A key benefit of format and concat is that we can save the output and copy it. Here we copy the strings to a byte vector.
vec
Vec extend_from_slice
fn main() { // Part 1: use format macro with an integer and an array. let value = 10; let value2 = [1, 2, 3]; let result = format!("Value is {} and value2 is {:?}", value, value2); println!("{}", result); // Part 2: use concat macro with constants. let result2 = concat!("Value is ", 100, " and value2 is ", 200); println!("{}", result2); // Part 3: copy the results to a byte vector. let mut copy = vec![]; copy.extend_from_slice(result.as_bytes()); copy.extend_from_slice(b"..."); copy.extend_from_slice(result2.as_bytes()); println!("{}", String::from_utf8_lossy(&copy).to_string()); }
Value is 10 and value2 is [1, 2, 3] Value is 100 and value2 is 200 Value is 10 and value2 is [1, 2, 3]...Value is 100 and value2 is 200
Summary. With the format and concat macros, we have an alternative to println. With these macros, we can store the resulting String, and use it elsewhere (or later) in our Rust program.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 17, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen