Example program. To begin, we introduce the append_string function. This receives 2 parameters: the mutable vector, and the string data we want to append.
Detail The buffer is a Vector that is modified by append_string, so we must pass it as a "mut" reference.
Tip When writing Rust, it is important to note the exact "mut" keyword usage. This is how Rust knows memory is changed (mutated).
Info Append_string is called with 2 arguments. In the program, we see that it appends the bytes from the strings to the vector.
Result We convert the Vector to a string by using from_utf8, and then unwrap(). The result is a merged string.
fn append_string(buffer: &mut Vec<u8>, data: &str) {
// Get bytes from string, and push them to the vector.
for value in data.bytes() {
buffer.push(value);
}
}
fn main() {
// Create a new vector, and append bytes from 3 strings to it.
let mut buffer = Vec::new();
append_string(&mut buffer, "soft");
append_string(&mut buffer, " orange");
append_string(&mut buffer, " cat");
// Print result as string from vector.
let result = String::from_utf8(buffer).unwrap();
println!("RESULT: {:?}", result)
}RESULT: "soft orange cat"
Notes, mut keyword. When we use the "mut" keyword to pass an argument, this indicates the function modifies the argument somehow. In append_string, the push() call modifies the buffer.
Extend from slice. There is a faster way to push bytes from a slice to a Vector. We can use the extend_from_slice function instead of a for-loop with push.
A summary. We built a helpful method that appends data from a string argument to a Vector of bytes. It loops over the strings, and appends the bytes.
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 Feb 24, 2023 (edit).