new lint: type_id_on_box

This commit is contained in:
y21 2023-06-18 22:20:10 +02:00
parent 3217f8aeaa
commit c5a9adc2be
7 changed files with 166 additions and 0 deletions

View file

@ -0,0 +1,20 @@
//@run-rustfix
#![warn(clippy::type_id_on_box)]
use std::any::{Any, TypeId};
fn existential() -> impl Any {
Box::new(1) as Box<dyn Any>
}
fn main() {
let any_box: Box<dyn Any> = Box::new(0usize);
let _ = (*any_box).type_id();
let _ = TypeId::of::<Box<dyn Any>>(); // don't lint, user probably explicitly wants to do this
let _ = (*any_box).type_id();
let any_box: &Box<dyn Any> = &(Box::new(0usize) as Box<dyn Any>);
let _ = (**any_box).type_id(); // 2 derefs are needed here
let b = existential();
let _ = b.type_id(); // don't lint
}

View file

@ -0,0 +1,20 @@
//@run-rustfix
#![warn(clippy::type_id_on_box)]
use std::any::{Any, TypeId};
fn existential() -> impl Any {
Box::new(1) as Box<dyn Any>
}
fn main() {
let any_box: Box<dyn Any> = Box::new(0usize);
let _ = any_box.type_id();
let _ = TypeId::of::<Box<dyn Any>>(); // don't lint, user probably explicitly wants to do this
let _ = (*any_box).type_id();
let any_box: &Box<dyn Any> = &(Box::new(0usize) as Box<dyn Any>);
let _ = any_box.type_id(); // 2 derefs are needed here
let b = existential();
let _ = b.type_id(); // don't lint
}

View file

@ -0,0 +1,25 @@
error: calling `.type_id()` on a `Box<dyn Any>`
--> $DIR/type_id_on_box.rs:13:13
|
LL | let _ = any_box.type_id();
| -------^^^^^^^^^^
| |
| help: consider dereferencing first: `(*any_box)`
|
= note: this returns the type id of the literal type `Box<dyn Any>` instead of the type id of the boxed value, which is most likely not what you want
= note: if this is intentional, use `TypeId::of::<Box<dyn Any>>()` instead, which makes it more clear
= note: `-D clippy::type-id-on-box` implied by `-D warnings`
error: calling `.type_id()` on a `Box<dyn Any>`
--> $DIR/type_id_on_box.rs:17:13
|
LL | let _ = any_box.type_id(); // 2 derefs are needed here
| -------^^^^^^^^^^
| |
| help: consider dereferencing first: `(**any_box)`
|
= note: this returns the type id of the literal type `Box<dyn Any>` instead of the type id of the boxed value, which is most likely not what you want
= note: if this is intentional, use `TypeId::of::<Box<dyn Any>>()` instead, which makes it more clear
error: aborting due to 2 previous errors