[英]Why does to_ascii_lowercase return a String rather than a Cow<str>?
str::to_ascii_lowercase
returns a String. str::to_ascii_lowercase
返回一个字符串。 Why doesn't it return a Cow<str>
just like to_string_lossy
or String::from_utf8_lossy
?为什么它不像
to_string_lossy
或String::from_utf8_lossy
那样返回Cow<str>
?
The same applies to str::to_ascii_uppercase
.这同样适用于
str::to_ascii_uppercase
。
The reason why you might want to return a Cow<str>
presumably is because the string may already be lower case.您可能想要返回
Cow<str>
大概是因为该字符串可能已经是小写了。 However, to detect this edge case might also introduce a performance degradation when the string is not already lower case, which intuitively seems like the most common scenario.但是,当字符串还不是小写时,检测这种边缘情况也可能会导致性能下降,这在直觉上似乎是最常见的情况。
You can, of course, create your own function that wraps to_ascii_lowercase()
, checks if it is already lower case, and return a Cow<str>
:当然,您可以创建自己的函数来包装
to_ascii_lowercase()
,检查它是否已经是小写,并返回Cow<str>
:
fn my_to_ascii_lowercase<'a>(s: &'a str) -> Cow<'a, str> {
let bytes = s.as_bytes();
if !bytes.iter().any(u8::is_ascii_uppercase) {
Cow::Borrowed(s)
} else {
Cow::Owned(s.to_ascii_lowercase())
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.