Why can fixed-size arrays be on the stack, but str cannot?

前端 未结 2 1209
醉话见心
醉话见心 2020-12-20 15:00

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

What is s

2条回答
  •  庸人自扰
    2020-12-20 15:27

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

    That's because you confused something here. The relationships are rather like this:

    • Vec[T]
    • Stringstr

    In all those four types, the length information is stored at runtime, not compile time. Fixed size arrays ([T; N]) are different in that regard: they store the length at compile time, but not runtime!

    And indeed, both [T] and str can't be stored on the stack, because they are both unsized.

    Could an str[N] type, which would be a shorthand to a [u8; N] that only contains provably valid UTF-8 encoded strings, replace str without breaking lots of existing code?

    It wouldn't replace str, but it could be an interesting addition indeed! But there are probably reasons why it doesn't exist yet, e.g. because the length of a Unicode string is usually not really relevant. In particular, it usually doesn't make sense to "take a Unicode string with exactly three bytes".

提交回复
热议问题