Home
Search
Rust push String bytes to Vec (u8)Add the bytes from a string to a u8 vector, merging strings together in a byte Vec.
Vector, u8 strings. Suppose 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.
Read Bytes
File create
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.
Mut 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).
Append_string This function 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.
Rust program that pushes string bytes to vector
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.
String Array
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.
extend from slice
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.
Home
© 2007-2022 sam allen.
see site info on the changelog.