I am quite new to Rust and have been trying to learn it, so sorry in case the question is trivial.
Strings and vectors are similar concepts in Rust. The "Rust Book" states: "Vectors are to slices what String is to &str". So why is the syntax so different?
While I agree that literals should be syntactically different (e.g. "1234" vs [1, 2, 3, 4]), I wonder why the other syntax should be so different when dealing with them.
To explain what I'm referring to, let's consider the following examples.
Example 1
let a = "1234";
let b = [1, 2, 3, 4];
This is ok: the syntax of the two statements is similar apart from the different literals.
Example 2
let a: &str = "1234";
let b: [i32; 4] = [1, 2, 3, 4];
This starts already to puzzle me. Why for the string I need to use the reference &
symbol, and why for the vector I need instead to specify the length? If the two concepts are similar (one is an array of chars, the other one an array of integers), why is the notation so different? I would have thought more clear to use for instance str
and vec
, so to write for instance:
let a: str(4) = "1234";
let b: vec[i32; 4] = [1, 2, 3, 4];
or:
let a: str = "1234";
let b: vec<i32> = [1, 2, 3, 4];
(in this case the length would have been inferred through initialization).
Example 3
let a = "1234".to_string();
let b = vec![1, 2, 3, 4];
Same question here. Couldn't we use str!("1234")
and vec![1, 2, 3, 4]
, or otherwise "1234".to_string()
and [1, 2, 3, 4].to_vector()
, or otherwise String("1234") and Vector[1, 2, 3, 4]
? (I would have liked the latter one the most).
Example 4
let a: String = "1234".to_string();
let b: Vec<i32> = vec![1, 2, 3, 4];
The two statements are even more different now... Couldn't we use either String
and Vector<i32>
, or Str
and Vec<i32>
etc.
Thanks