How can i do instance of

Hey rust master

i have a quick question that i am wondering how to do it in rust

i have a function that checks if a user exists, like this

    /// Check if user exists or not.
    ///
    /// # Arguments
    ///
    /// * `value` - can be: username | email | uid
    pub fn exists(value: &str) -> bool {
        use crate::schema::users::dsl::*;

        let conn = db::pg_connection();
        let filter = users.filter(username.eq(&value))
            .or_filter(email.eq(&value))
            .or_filter(uid.eq(value));                    // <= error

        diesel::select(diesel::dsl::exists(filter))
            .get_result(&conn)
            .unwrap()
    }

where value can be &str or uuid::Uuid i know that there is generics in rust, but wondering how can i check if type belongs to Uuid and not &str

is there a way in rust, like instanceof in php, if not how can i achieve the behavior i want using rust?

If you want the function to accept values of Uuid as well, you could make an enum and take that:

enum Value<'a> {
    Str(&'a str),
    Uuid(Uuid),
}

pub fn exists<'a>(value: Value<'a>) -> bool {
    let conn = db::pg_connection();
    match value {
        Str(s) => ...  // s is a &str
        Uuid(u) => ...  // uuid is a Uuid
    }
}

You could also implement From<&str> and From<Uuid> for Value, then make exists take a generic V: Into<Value>, so that you can call exists directly with either a &str or Uuid. It really depends on how you're calling this exists function, though.

3 Likes

@asymmetrikon thank you for your response :slight_smile:

this is how i intend to call exists

    #[test]
    fn one() {
        init();

        let user: User = FakeUser::one();
        let exists = User::exists(&user.username);

        assert!(exists);
    }

Rust doesn't have function overloading. The recommended approach is to simply make three functions as such:

User::username_exists(...)
User::uid_exists(...)
User::email_exists(...)

You could have a fourth internal method to avoid repeating yourself, that each of the three above then call.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.