Coming from a C background, where memory is explicitly cleaned up, it's not uncommon to have the same struct used in two different ways: akin to Rust's borrowing vs taking ownership. This doesn't just apply to the struct but the values it holds.
So in C, the same struct may be used to pass "borrowed" references or pass ownership:
struct Foo {
char * a;
char * b;
}
But in rust I need to declare whether strings in a struct are owned by the struct or not:
// Pass ownership
struct Foo {
a: String,
b: String,
}
// Just pass a borrowed reference to the data
struct Foo<'a> {
a: &'a str,
b: &'a str,
}
Since parsing functions need to pass ownership, I assume the "normal" thing to do is have a struct that passes ownership:
struct Foo<'a> {
bar: String,
baz: String,
}
fn parse_foo(source_data: &[u8]) -> Result<Foo, SomeErrorType> {
// ...
}
fn format_foo(mut target: Vec<u8>, value: &Foo) -> Result<(), SomeErrorType> {
// ...
}
The "problem" I'm puzzling over:
In the above example, when code want's call format_foo()
it must assemble a Foo {...}
and so pass ownership of the strings. This only happens because the same Foo
is also used for parse_foo
which MUST pass ownership. On it's own format_foo()
, it could be written to only accept borrowed references to everything.
Does this typically leed to a little more memory copying in Rust. Is that copying just a normal fact of Rust over a language like C? Is there some other patten I've missed (like having two similar sucts).
Just to be very clear, this isn't a critisizm of Rust, I'm just trying to get to grips with what "normal" patterns look like in Rust.