Vector
, u8
stringsSuppose we have a byte
vector (with u8
elements) in Rust. We want to append strings as byte
data to the vector.
With a helper method, we can loop over strings (or other kinds of arguments) and push u8
elements. We must pass the vector as a mutable reference.
To begin, we introduce the append_string
function. This receives 2 parameters: the mutable vector, and the string
data we want to append.
Vector
that is modified by append_string
, so we must pass it as a "mut
" reference.mut
" keyword usage. This is how Rust knows memory is changed (mutated).Append_string
is called with 2 arguments. In the program, we see that it appends the bytes from the strings to the vector.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"
mut
keywordWhen 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.
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.
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.