【发布时间】:2021-10-29 20:32:48
【问题描述】:
我正在尝试创建一个函数,给定一个回调,它可以对字符串执行一些操作,并且如果它需要一些修改,则返回一个新分配的副本。我正在使用 std::borow::Cow 来处理这样的事情,但是当我尝试使用回调来更改对字符串执行该操作的方式时,问题就来了。
这是我正在尝试做的一个简化示例:
use std::borrow::Cow;
pub enum Error {
Test,
}
fn do_lower_case<'a> (s: &'a str) -> Result<Cow<'a, str>, Error>
{
let s = s.to_lowercase();
Ok(s.into())
}
fn say_hello<'a>(
f: impl Fn(&'a str) -> Result<Cow<'a, str>, Error>,
) -> Result<Cow<'a, str>, Error>
{
let s = String::from("Hello");
// Problem: We can not call the callback from here.
// Nevertheless we can call do_lower_case
let s = f(&s)?; // Comment this and uncomment next line works
//let s = do_lower_case(&s)?;
let s = s.into_owned();
Ok(s.into())
}
fn main() {
let res = say_hello(do_lower_case); // Callback is provided here
match res {
Ok(s) => println!("Result: {}", s),
Err(_) => println!("Could not do anything!"),
}
}
这样的事情可以在 Rust 中完成吗? 这是一个生锈游乐场的链接: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8607d8ac4c34d02236e82e30bcf51e2e
【问题讨论】: