ExpHP
December 31, 2017, 2:07am
1
I just spotted this crazy syntax for initializing and pattern matching tuple structs and newtypes in the Rust reference .
#[derive(Eq, PartialEq, Debug)]
struct Wat(u32);
fn main() {
assert_eq!(
Wat(32),
Wat { 0: 32 } // wat
);
match Wat(32) {
Wat { 0: 32 } => {},
_ => panic!(),
}
}
5 Likes
Considering that tuple struct field accesses works via numbers, i.e. assert_eq!(wat.0, 32)
, a corresponding initialization syntax doesn't seem all that farfetched to me.
xfix
December 31, 2017, 1:02pm
4
This can be used with struct update syntax as well.
#[derive(Debug)]
struct Type(i32, i32, i32, i32, i32, i32, i32, i32, i32, i32);
fn main() {
let x = Type(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
let y = Type { 1: 5, ..x };
println!("{:?}", y);
}
This is useful when dealing with macros, as tuples don't have to special cased.
2 Likes
matklad
December 31, 2017, 1:38pm
5
struct S(i32);
fn foo(s: S) {
let x: i32 = s.0000000000000000000000000000000000000000000000000000000000000;
}
This is a reported bug though, hopefully it'll get fixed soon.
1 Like