Rust 中的 `str` 有什么用吗?
Is there any use for `str` in Rust?
有没有不用借用就用str
的情况?这有意义吗?
我明白String
和&str
的区别,但是既然有&str
就一定有str
?
您不能对类型 str
的 值 做太多事情,但是在很多情况下您会想要引用类型 [=11] =].
Box<str>
或 Rc<str>
- 拥有的类型,类似于 String
,但不能突变以增长或重新分配
任何时候你想接受一个可以查看的任意类型作为字符串,你可以使用像T: Deref<Target = str>
、T: AsRef<str>
或 T: Borrow<str>
。例如 HashMap::get
具有以下签名:
pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where
K: Borrow<Q>, // K is the key type for the HashMap
Q: Hash + Eq,
这意味着您可以使用 HashMap<String, i32>
,但可以使用 &str
键访问值,例如map.get("key")
。这里 Q
将被推断为 str
,但 k
参数仍将是 &str
(&Q
).
?Sized
注释意味着 Q
不需要在编译时知道大小,明确允许使用未确定大小的类型,如 str
。
因为 str
未调整大小 (?Sized) meaning the size at compile time is not known. You can only use it in places where ?Sized
is allowed. That is the case in Box.
let s: &str = "any string";
let box: Box<str> = Box::from(s);
因为 box 在堆上分配数据,所以它不关心在编译时是否知道类型的大小。
你可以看到String::into_boxed_str中使用了Box<str>
,如果你想说,我已经完成生成字符串并且不想添加任何内容,这很有用它。此外,它删除了 String
需要的容量字段,从而节省了一些内存。但是我还没有真正看到这个用得太多。
大多数你会看到 str
而没有 &
的地方都是在具有泛型类型的特征中。例如在实施 AsRef.
时
pub struct CustomString(String);
impl AsRef<str> for CustomString {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
旁注:str
的行为类似于未调整大小的切片 [T]
(?Sized
)。
有没有不用借用就用str
的情况?这有意义吗?
我明白String
和&str
的区别,但是既然有&str
就一定有str
?
您不能对类型 str
的 值 做太多事情,但是在很多情况下您会想要引用类型 [=11] =].
Box<str>
或Rc<str>
- 拥有的类型,类似于String
,但不能突变以增长或重新分配任何时候你想接受一个可以查看的任意类型作为字符串,你可以使用像
T: Deref<Target = str>
、T: AsRef<str>
或T: Borrow<str>
。例如HashMap::get
具有以下签名:pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, // K is the key type for the HashMap Q: Hash + Eq,
这意味着您可以使用
HashMap<String, i32>
,但可以使用&str
键访问值,例如map.get("key")
。这里Q
将被推断为str
,但k
参数仍将是&str
(&Q
).?Sized
注释意味着Q
不需要在编译时知道大小,明确允许使用未确定大小的类型,如str
。
因为 str
未调整大小 (?Sized) meaning the size at compile time is not known. You can only use it in places where ?Sized
is allowed. That is the case in Box.
let s: &str = "any string";
let box: Box<str> = Box::from(s);
因为 box 在堆上分配数据,所以它不关心在编译时是否知道类型的大小。
你可以看到String::into_boxed_str中使用了Box<str>
,如果你想说,我已经完成生成字符串并且不想添加任何内容,这很有用它。此外,它删除了 String
需要的容量字段,从而节省了一些内存。但是我还没有真正看到这个用得太多。
大多数你会看到 str
而没有 &
的地方都是在具有泛型类型的特征中。例如在实施 AsRef.
pub struct CustomString(String);
impl AsRef<str> for CustomString {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
旁注:str
的行为类似于未调整大小的切片 [T]
(?Sized
)。