Re:Rust for C++ programmers – part 2: control flow
by bjz_ on Sunday April 20, 2014 @09:18AM
(#7616689)
Showing let bindings with their explicit type declarations might help:
The pattern binding goes to the left of the `:`, and the input type goes to the right. Also note that you can pattern match on types too:
[ Parent
| on HN ]
Re:Rust for C++ programmers – part 2: control flow
by acqq on Sunday April 20, 2014 @10:08AM
(#7616802)
Thanks, if _ is allowed as the type, why are explicit types written at all?
Is the last example equivalent to
let (mut x, ref y, &z): (_, _, &_) = (1, 2, &3);
and can we go even further let (mut x, ref y, &z) = (1, 2, &3);
If we can, when do we actually need specifying the types? To do the type conversion or what?Probably because I don't know Haskell (sorry) but I still imagine x y and z as names and even mut, ref and & as the "access" specifications, which define somehow the "type" of x y and z and not the type the thing accessed with the given name.
Re:Rust for C++ programmers – part 2: control flow
by bjz_ on Sunday April 20, 2014 @11:18AM
(#7617025)
I might not have been clear enough. I was just trying to show how the current syntax fits in with `:`, and why your suggestions for `: mut` would not fit with that. All of these are valid Rust code:
let (mut x, ref y, &z): (int, int, &int) = (1, 2, &3);
let (mut x, ref y, &z): (_, _, &_) = (1, 2, &3);
let (mut x, ref y, &z) = (1, 2, &3);
The types are still the same in each case. No conversions or dynamic typing is happening in any of them - they are all statically typed.Rust, like Haskell and ML, uses an advanced form of type reconstruction called Hindley-Milner[0] type inference. This is a constraint solving algorithm that can deduce types from very little information. Sometimes you do need to add some annotations though to help the inference along a little, but that is very rare (although more common in Rust than in Haskell or ML).
The grammar could be expressed as:
'let' <pattern> (':' <type>)? '=' <expr>
Where `<type>` is the type of the expression to the right of the `=`. As I said before: in practice it is very rare to explicitly annotate a `let` binding.