Vojislav Stojkovic
Vojislav Stojkovic

Reputation: 8153

How to write a generic function with a type parameter that satisfies its own Self bound?

I'm trying to write a function that receives a mutable reference to a generic struct from someone else's crate (so I can't modify that struct's definition). Some of the methods implemented for the struct are only available when the struct satisfies a certain bound:

impl<'s, 'p: 's, P> TryCatch<'s, P>
where
  Self: AsMut<HandleScope<'p, ()>>,
{
    // functions that I want to use
}

My function works fine if I declare it like this:

fn my_func(try_catch: &mut v8::TryCatch<v8::HandleScope>)

or like this:

fn my_func(try_catch: &mut v8::TryCatch<v8::EscapableHandleScope>)

Since there's no function overloading in Rust, I have to either write two functions, write my own trait and then implement it for both flavors of TryCatch, or come up with some clever way to make the compiler accept either flavor as an argument.

I can pick either of the first two options and it's not a big deal, but I'm trying to learn Rust better, and I was wondering if anyone could help me get the third option working.

PS: Sorry for the clumsy title. If there's a better way to phrase it, let me know.

Upvotes: 1

Views: 844

Answers (1)

Jbat1Jumper
Jbat1Jumper

Reputation: 11

You can achieve what you want also making your function generic. I don't know your particular case, but for instance, both v8::HandleScope and v8::EscapableHandleScope implement the v8::Scoped trait.

So if that's all you need to know about that type you can rewrite your function like:

fn my_func<S>(try_catch: &mut v8::TryCatch<S>)
where
    S: v8::Scoped 

or more shortly:

fn my_func<S: v8::Scoped>(try_catch: &mut v8::TryCatch<S>)

Upvotes: 1

Related Questions