3 ms·
> Is this because args() ultimately gives you a String Correct. > Why does args() give you String rather than str? Because the command-line arguments to th
by steveklabnik 11y ago
> Is this because args() ultimately gives you a String
Correct.
> Why does args() give you String rather than str?
Because the command-line arguments to the program are dynamically created. To be a &'static str, like a literal, they would have to be baked into the binary. &str is a pointer, it doesn't own any backing store.
> Would there be any way to turn the output of args straight into a &str, so you didn't need to .into() the literal?
Well, so that is what this code is doing. It's just also handling error cases: What if the argument isn't passed in, as the primary one.
> Why are String and str separate types, rather than different uses of a single type?
Because String actually owns the data it's attached to, and is heap-allocated. &str is a pointer; it can only point at some other string type, since it doesn't store its own data.
> Are there any other examples of pairs of types with the same relationship?
Arrays/Vectors and slices are a great example: String is wrapper around Vec<u8>, and &str one around &[u8]. But any owned/pointer variant with some sort of restriction on the type of data is going to be like this, it's a pretty common pattern.
Don't forget other string types too: There's OSString, CString, and external crates provide other types as well. Strings are not simple.
> Is there something like this for maps/dictionaries/hashes?
Slices point to _contiguous_ spots in memory, so these data types don't really have slices, because that property isn't true.
> I would be equally grateful for a link to some relevant documentation or whatever as for a detailed answer!
Hehe, no worries. It's hard to say what _specifically_ would be the best docs, but if you're interested in the _future_ docs about this, http://rust-lang.github.io/book/understanding-ownership.html http://rust-lang.github.io/book/understanding-ownership.html is an explanation of Rust's ownership system through String and &str that will become the next version in the official docs. There's still some rough edges, as it's a draft, though!