Skip to content

Add an error return method to format #3206

@cheeroncode

Description

@cheeroncode

Add an error return method to format!
The format! macro never fails and the compiler reports an error when it does.

let a:String = format!("{}",9);

Sometimes, however, I may need to reorganize the formatted string in a custom program macro based on user input.
When the user typed something wrong, I wanted to catch the compiler error and re-report the error in the right place.
I wish there was a way to return the wrong or a way to do this, thanks a lot.

let b:Result<String,String> = try_format!("{:?}",9);
match b {
    Ok(ok) => {
        // do something...
    },
    Err(err) => {
        // Custom error handling...
    },
} 

Here's a scenario that could go wrong to make my intentions more obvious.

I provide my users with a macro called comment!, which takes a format argument like format! :

#[comment("{:1$}","hi~",10)]
fn do(){
    //....
}

comment! inserts a new line of code into method do :

fn do(){
    println!("{:1$}","hi~",10);
    //....
}

If the user accidentally enters formatting parameters incorrectly:

#[comment("{:$}","hi~",10)]
           ^^^^
fn do(){
    //....
}

Then, the newly generated code will be wrong.
The compiler will give a vague error on #[comment(...)] and cannot indicate the correct location:

fn do(){
    println!("{:$}","hi~",10); // ^^^^ section is what actually went wrong, missing the width index.
              ^^^^             
    //....
}          

Now, I want to check that the formatting parameters are correct when I generate 'println'.
I think the best way is to catch any errors the compiler gives you,
And display the error in the corresponding position of comment! :

#[comment("{:$}","hi~",10)]
           ~~~~
fn do(){
    //....
}

So, I wish there was a try_format!.
When the parameter is not correct, can return an error, let me control.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions