idanarye/rust-typed-builder

Any plans on moving string allocation inside TypedBuilder?

alekspickle opened this issue · 4 comments

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.

Try this:

#[derive(TypedBuilder)]
struct Type {
    #[builder(setter(into))]
    field1: String
}

https://docs.rs/typed-builder/latest/typed_builder/derive.TypedBuilder.html#customisation-with-attributes

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

Works for me, but arguably can be easier. 😬