Consider this code sample
#[derive(Debug)] struct PlainStruct { x: i32 }
#[derive(Debug)] struct TupleStruct ( i32 );
impl PlainStruct { fn new(x: i32) -> PlainStruct { PlainStruct { x } } }
impl TupleStruct { fn new(x: i32) -> TupleStruct { TupleStruct ( x ) } }
fn main() {
println!("{:?}", PlainStruct::new(2));
println!("{:?}", TupleStruct::new(2));
}
which
- defines two almost identical struct types
- instantiaties them and
- prints them out using the
Debug
trait.
The only difference between the structs is whether they were implemented as a tuple struct or not.
In the case of the tuple struct, the compiler is happy; in the case of the non-tuple struct it complains that the field is never read, even though it is printed out at run time.
Does this make sense, or is this a bug in the dead code analysis?
The tuple struct doesn't have a name referring to the field that is supposedly unused, so maybe that's why behaviour is inconsistent across the two cases. Indeed, in code that really doesn't use the fields
struct PlainStruct { x: i32 }
struct TupleStruct ( i32 );
impl PlainStruct { fn new(x: i32) -> PlainStruct { PlainStruct { x } } }
impl TupleStruct { fn new(x: i32) -> TupleStruct { TupleStruct ( x ) } }
fn main() {
PlainStruct::new(2);
TupleStruct::new(2);
}
the compiler also only complains about PlainStruct
's field not being used, and doesn't mention TupleStruct
.
So
- In the first case there seems to be an erroneous complaint about
x
not being read. (It is, when it is printed out via `Debug'.) - In the second case there is a lack of warning about an unused 'field'.
[Aside: is there some terminology for non-tuple-struct, i.e. the thing I have called PlainStruct
in the code sample?]