Need compact way to turn off warning `field X never used`

In my proc macro I have an attribute dynamic_field, this attribute allows to ignore struct field and use struct method with same name instead. But on compile I have a warning: field X never used. For now I can fix it by apply #[allow(dead_code)]:

#[derive(WorldPacket)]
#[options(no_opcode)]
struct Income {
    message_type: u8,
    language: u32,
    skip: u32,
    #[allow(dead_code)]
    #[dynamic_field]
    channel_name: String,
    target_guid: u64,
    message_length: u32,
    #[allow(dead_code)]
    #[dynamic_field]
    message: String,
}

impl Income {
    fn message<R: BufRead>(mut reader: R, initial: &mut Self) -> String {
        let mut buffer = vec![0u8; initial.message_length as usize];
        reader.read_exact(&mut buffer).unwrap();
        String::from_utf8(buffer).unwrap()
    }

    fn channel_name<R: BufRead>(mut reader: R, initial: &mut Self) -> String {
        if initial.message_type == MessageType::CHANNEL {
            let mut buffer = Vec::new();
            reader.read_until(0, &mut buffer).unwrap();
            String::from_utf8(buffer).unwrap()
        } else {
            String::default()
        }
    }
}

but probably there another more compact way exists (instead of applying #[allow(dead_code)] to each field) ? Could somebody explain about that ?

P.S. I do not need to turn off this warning globally, because I still want to catch this warning in other parts of code. I want to turn off this warning only for structs affected by my proc macro.

You can add #[allow(dead_code)] to your struct instead of the fields like this:

#[derive(Default)]
#[allow(dead_code)]
struct Income {
    message_type: u8,
    language: u32,
    skip: u32,
    channel_name: String,
    target_guid: u64,
    message_length: u32,
    message: String,
}

fn main() {
    let _ = Income::default();
}

This doesn't raise any dead code warnings in the playground.

You can read more about attributes like #[allow(...)] here.

Edit: you can find more about the lint attributes warn, deny, allow and forbid also in the reference.

2 Likes