Any plans on moving string allocation inside TypedBuilder?
alekspickle opened this issue · 4 comments
alekspickle commented
It'll just be nice to use it like this:
let type = Type::builder().field1("value");
Instead of adding to_string\to_owned
each time.
Logarithmus commented
Try this:
#[derive(TypedBuilder)]
struct Type {
#[builder(setter(into))]
field1: String
}
mo8it commented
I can confirm that #[builder(setter(into))]
works. The issue can be closed.
mo8it commented
@alekspickle In this case, I would actually recommend using Cow<'a, str>
to avoid unneeded allocations:
use std::borrow::Cow;
use typed_builder::TypedBuilder;
#[derive(TypedBuilder)]
struct CowHolder<'a> {
#[builder(setter(into))]
s: Cow<'a, str>,
}
fn check_cow(cow: Cow<str>) {
match cow {
Cow::Borrowed(s) => println!("Borrowed: {}", s),
Cow::Owned(s) => println!("Owned: {}", s),
}
}
fn main() {
let borrowed_cow = CowHolder::builder().s("Muuuh").build();
check_cow(borrowed_cow.s);
let owned_cow = CowHolder::builder().s(format!("{:u<10}h", "M")).build();
check_cow(owned_cow.s);
}
Output:
Borrowed: Muuuh
Owned: Muuuuuuuuuh
alekspickle commented
Works for me, but arguably can be easier. 😬