The snippet below try to call multiple functions returning Cow
s inside a workflow control function (Or namely chaining Cow
s?). If every process function f1
, f2
, f3
... rarely return a owned value, f
should be able to return the input borrow value.
How can I fix this issue? Or any suggestion to improve this workflow? Thanks.
use std::{borrow::Cow, ops::Deref};
fn f1(s: &str) -> Cow<'_, str> {
if s == "hello" {
Cow::Owned(s.to_uppercase())
} else {
Cow::Borrowed(s)
}
}
fn f2(s: &str) -> Cow<'_, str> {
if s.contains(' ') {
Cow::Owned(s.to_string().replace(' ', ""))
} else {
Cow::Borrowed(s)
}
}
// Or maybe more...
// fn f3(s: &str) -> Cow<'_, str> {
// ...
// }
fn f(s: &str) -> Cow<'_, str> {
let s = f1(s);
let s = f2(s.as_ref()); // let s = f2(s.deref()); won't work
// ...
// let s = f3(s.as_ref());
s // cannot return value referencing local variable `s`
}
fn main() {
let s = "hello world";
f(s);
let s = "abc";
f(s);
}