【发布时间】:2018-09-18 20:24:28
【问题描述】:
我正在 Parser 结构中实现代码解析器。我公开了一个 pub 方法 lines 来迭代删除 cmets 的代码行。我想返回一个Box<Iterator>
extern crate regex; // 1.0.5
use regex::Regex;
pub struct Parser {
code: String,
}
static comment: Regex = Regex::new(r"//.*$").unwrap();
impl Parser {
pub fn new(code: String) -> Parser {
Parser { code }
}
pub fn lines(&self) -> Box<Iterator<Item = &str>> {
let lines = self
.code
.split("\n")
.map(|line| comment.replace_all(line, ""));
Box::new(lines)
}
}
但是,编译器给出了这个错误:
error[E0271]: type mismatch resolving `<[closure@src/lib.rs:20:18: 20:54] as std::ops::FnOnce<(&str,)>>::Output == &str`
--> src/lib.rs:21:9
|
21 | Box::new(lines)
| ^^^^^^^^^^^^^^^ expected enum `std::borrow::Cow`, found &str
|
= note: expected type `std::borrow::Cow<'_, str>`
found type `&str`
= note: required because of the requirements on the impl of `std::iter::Iterator` for `std::iter::Map<std::str::Split<'_, &str>, [closure@src/lib.rs:20:18: 20:54]>`
= note: required for the cast to the object type `dyn std::iter::Iterator<Item=&str>`
它希望我使用std::borrow::Cow,但我在the Map docs 中找不到任何提及此要求的内容。为什么这是必要的?我可以避免吗?
【问题讨论】:
-
Idiomatic Rust 使用
snake_case表示变量、方法、宏和字段;UpperCamelCase用于类型;SCREAMING_SNAKE_CASE用于静态和常量。请改用static COMMENT。
标签: rust