Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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

What is surprising is that a str is more limited than a fixed-sized array, because it cannot be declared as a local variable. Compiling

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

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

in Rust 1.32.0, I get

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

which is confusing, because the size of "apple" can be known by the compiler, it is just not part of the str type.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

  • Vec<T> ? [T]
  • String ? str

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[5] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

57.0k users

...