Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

question mark operator (?) before variables – what do they do in rust?

I’m improving my rusty skills lately and saw (in some Copilot suggestions) the question mark operator used as a prefix of variables:

debug!(?raw); // raw is of type String

// Also

match self.subnet_tx.send((raw, addr)) {
    Ok(_size) =>  continue,
    Err(err: SendError<(String, SocketAddr)>) => {
        error!(cause = ?err, "error sending to channel");
        continue;
    }
};

Obviously I googled it and read about the ? operator – yet, I could not find any useful information about that.

The closest piece of information I did find was related to the ?Sized trait.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can anyone explain what is it used for? Should it be used? In which cases?

Thanks.

>Solution :

There is no "question mark before variables" in rust. However it can be used as a token in macros and seeing that your code uses it only in macros I believe that is the case here. If you would provide where debug and error macro come from it could be confirmed.

EDIT. Those macros are from tracing crate. As the documentation says:

The ? sigil is shorthand that specifies a field should be recorded using its fmt::Debug implementation

So this is not some general convention, but rather some specific syntax that designers of tracing crate chose.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading