And yes, this is producing a fixed-size array on the stack; in this case the length of the array is being inferred based on the type provided in the assertion.
Note that this inference is static, and the compiler would tell you if it didn't have something concrete to infer the type from. The type inference is also limited to the function body, so removing the assertion could only ever cause an effect in that single function.
> Does Rust do this kind of look-ahead inference a lot
Yes, but it's important to note that type inference in Rust is function-local. Furthermore, crucially, Rust requires types to be explicitly specified at function boundaries. Altogether this means that you (and the compiler) don't need to look farther than the function signature to figure out a given type.
This means that you can do stuff like this:
let mut foo = HashMap::new();
foo.insert("bar", true);
Despite the fact that HashMap is a generic type, nowhere do we need to specify that this particular instance has string keys and Boolean values, because the type of the map is inferred from its usage. In languages with only statement-local type inference, you'd need to specify the type of the elements at the point of construction.
This isn't so bad except in the case where a developer puts off the resolving statement until later in the function, though I imagine (hope) there is almost never a legitimate reason to do that.
Is it theoretically possible to split the resolution into two lines? Then, as a reader, it might not always be obvious at what point the type is fully resolved.
E.g (pseudocode, and also it makes no practical sense since you would have populated it before interrogating it).
let mut foo = HashMap::new();
print(foo.containsKey("bar")); // here we've resolved the key type
print(foo.containsValue(true)); // here we've resolved the value type
> Then, as a reader, it might not always be obvious at what point the type is fully resolved.
This is rarely a problem, because Rust is strict enough that it will tell you if your types aren't lining up like you think they are. And if you're using an editor with LSP support, then you can have inlay hints that reveal the types of all variables if you like.
I personally prefer the following style instead of comprehensions
let my_arr = [1, 2, 3, 4, 5];
my_arr.iter().map(|x| x + 1).for_each(
|item| println!("The Value of this item is {item}")
);
the map statement allows for one liners, like list comprehensions, with the added benefit of semantics like being able to chain operations into pipelines.
I gave your comment a dislike for the reason that pasting in responses from chatGPT should not be commin practice here. It’s only polluting the comment section in my opinion.
https://doc.rust-lang.org/std/array/fn.from_fn.html