Home
Rust
Vec push: Add u8 From String
This page was last reviewed on Feb 24, 2023.
Dot Net Perls
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.
File 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.
Detail The buffer is a Vector that is modified by append_string, so we must pass it as a "mut" reference.
mut
vec
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.
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.
Vec 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 24, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.