Rust错误E0277:无法比较str与&str,正确做法是什么?
问题
尝试将字符串切片的切片与&'static str比较时遇到编译错误,代码如下:
impl Tag for BoldTag { fn is_this_tag(text_slice: &str) -> bool { text_slice.len() >= 2 && text_slice[0..=1] == "**" } }
编译错误信息:
error[E0277]: can't compare `str` with `&str` --> src/lib.rs:52:52 | 52 | text_slice.len() >= 2 && text_slice[0..=1] == "**" | ^^ no implementation for `str == &str` | = help: the trait `PartialEq<&str>` is not implemented for `str` = help: the following other types implement trait `PartialEq<Rhs>`: <&'a str as PartialEq<OsString>> <&'a str as PartialEq<String>> <&'b str as PartialEq<Cow<'a, str>>> <String as PartialEq<&'a str>> <String as PartialEq<Cow<'a, str>>> <String as PartialEq<str>> <String as PartialEq> <str as PartialEq<Cow<'a, str>>> and 4 others
疑惑点:
- 为什么
&str的切片结果是str而非&&str? - 如何正确编写这个判断函数?
解答
为什么切片后是str而不是&&str?
text_slice的类型是&str,本质是指向底层字符串数据的引用。当使用[0..=1]切片时,Rust针对&str的切片语法返回的是str类型的临时值——但str是动态大小类型(DST),无法直接存放在栈上,所以这里实际是未被引用的str临时对象,而非对&str的引用(&&str)。
由于PartialEq未实现str == &str的比较逻辑,因此编译器报错。
正确的写法
有两种常见的解决方式:
方式1:给切片结果加引用
直接对切片结果取引用,将其转为&str,即可和右侧的"**"(类型&'static str)比较:
impl Tag for BoldTag { fn is_this_tag(text_slice: &str) -> bool { text_slice.len() >= 2 && &text_slice[0..=1] == "**" } }
方式2:使用starts_with方法(更简洁安全)
Rust的&str提供了starts_with方法,专门用于判断字符串是否以指定前缀开头,无需手动处理索引和长度判断:
impl Tag for BoldTag { fn is_this_tag(text_slice: &str) -> bool { text_slice.starts_with("**") } }
该方法会自动处理字符串长度不足的情况,代码更健壮。
内容的提问来源于stack exchange,提问作者verified_tinker
相关产品推荐
相关产品推荐

