Array of different lifetime element to array of cow

I need to return a list of Cow<str> from a function, but my strs have different lifetimes. Before they had different lifetime, I could just map to Cow::from, but now I need to specify for each element:

        [
            Cow::from(format!("{}", self.id)),
            Cow::from(amount_string),
            Cow::from(self.description.to_string()),
            Cow::from(self.receiver.to_string()),
            Cow::from(format!("{}", self.date.format("%v %H:%M"))),
            Cow::Borrowed(&self.account.name),
            Cow::from(acc_string),
        ]
        .into_iter()
        // .map(Cow::from)
        .collect()

Is there a way for the map to know when to Borrow and when to take ownership ?
Thank you

You can't have both Strings and &strs in the array (or iterate over more than one type either).

Could you clarify what you're trying to accomplish? You already have an array of Cows and from it you create an iterator of Cows and collect it into a collection (say, Vec<Cow<str>>). So why do you want to use map(Cow::from)? What do you want to do that's different from, say:

vec![
    Cow::from(format!("{}", self.id)),
    Cow::from(amount_string),
    Cow::from(self.description.to_string()),
    Cow::from(self.receiver.to_string()),
    Cow::from(format!("{}", self.date.format("%v %H:%M"))),
    Cow::Borrowed(&self.account.name),
    Cow::from(acc_string),
]

?

If the type of the resulting vector is explicitly annotated as Vec<Cow<'_, str>>, then you can replace all the Cow::from()s with .into()s:

let list: Vec<Cow<'_, str>> = vec![
    format!("{}", self.id).into(),
    amount_string.into(),
    self.description.to_string().into(),
    self.receiver.to_string().into(),
    format!("{}", self.date.format("%v %H:%M")).into(),
    (&self.account.name).into(),
    acc_string.into(),
];
1 Like