Answers to What are the differences between Rust's `String` and `str`? describe how &str and String relate to each other.

令人惊讶的是,str比固定大小的数组更有限,因为它不能声明为局部变量.汇编

let arr_owned = [0u8; 32];
let arr_slice = &arr_owned;

let str_slice = "apple";
let str_owned = *str_slice;

在Rust 1.32.0中,我得到

error[E0277]: the size for values of type `str` cannot be known at compilation time
 --> src/lib.rs:6:9

这让人困惑,因为编译器可以知道"apple"的大小,但它不是str类型的一部分.

Is there a linguistic reason for the asymmetry between Vec<T> <-> [T; N] and String <-> str owned types? Could an str[N] type, which would be a shortand to a [u8; N] that only contains provably valid UTF-8 encoded strings, replace str without breaking lots of existing code?

推荐答案

asymmetry between Vec<T> <-> [T; N] and String <-> str

那是因为你搞糊涂了.它们之间的关系是这样的:

  • Vec<T>[T]
  • Stringstr

在这四种类型中,长度信息都存储在运行时,而不是编译时.固定大小数组(([T; N])在这方面有所不同:它们在编译时存储长度,但在运行时不存储长度!

实际上,[T]str都不能存储在堆栈上,因为它们都没有大小.

str[N]类型是[u8; N]的简写,它只包含可证明有效的UTF-8编码字符串,能在不 destruct 大量现有代码的情况下替换str吗?

它不会取代str,但它确实是一个有趣的补充!但它还不存在可能有一些原因,例如,因为the length of a Unicode string is usually not really relevant.特别是,通常"使用一个只有三个字节的Unicode字符串"是没有意义的.

Rust相关问答推荐

SQL x中的mut *transaction和mut transaction有什么区别?

使用Rust s serde_json对混合数据类型进行优化'

如何创建引用构造函数拥有的变量的对象?

这种获取-释放关系是如何运作的?

编译项目期间使用Cargo生成时出现rustc错误

有没有办法避免在While循环中多次borrow `*分支`

如何定义实现同名但返回类型不同的 struct 的函数

在Rust中判断编译时是否无法访问

应为关联类型,找到类型参数

从 rust 函数返回 &HashMap

Rust Option 的空显式泛型参数

如何从borrow 的异步代码运行阻塞代码?

在描述棋盘时如何最好地使用特征与枚举

Google chrome 和 Apple M1 中的计算着色器

如果不满足条件,如何在 Rust 中引发错误

如何使返回 XMLError 的方法与 anyhow::Error 兼容?

If let expression within .iter().any

为什么 no_std crate 可以依赖于使用 std 的 crate?

需要括号的宏调用中的不必要的括号警告 - 这是编写宏的糟糕方法吗?

为什么 `ref` 会导致此示例*取消引用*一个字段?