Crate with macro for creating a one-use type and an instance of it at the same time?


#1

Hi there!

From time to time I need to create a type just to use it once. As an example, I’m using diesel right now to talk to a database. To insert a new entity into the database I write create() methods for my types. For example, my User::create() method looks like:

#[derive(Clone, Insertable)]
#[table_name = "users"]
struct NewUser {
    name: String,
}

let new_user = NewUser { name: new_name };
diesel::insert(&new_user) /* ... */

I create a type definition and use it to create one instance. But other than that, I don’t need the type at all. So I already wrote a hacky macro to do both at once. Something like:

let new_user = adhoc! {
    #[derive(Clone, Insertable)]
    #[table_name = "users"]
    struct User {
        name: String = new_name,
    }
};

So my question is: is there already a crate offering such a macro? If not, do you agree with me that this is a useful thing to have?


#2

So basicaly you have code like this:

fn save_user(name: String) {
    struct NewUser {
        name: String,
    }
    let new_user = NewUser { name };
}

From support code point of view this is clean and obvious code,
while with adhoc! macros it is complelty not clear what is going on.

But may be if you going to write some prototype and then throught it away,
it is better to use any tools that speedup code writing include custom macroses.