Would something like javascript Proxy be viable in Rust?

I've been using the newtype pattern quite often latelly, especially when trying to get around the orphan rule, I'm starting to think that something like javascript proxy would be great in combination with newtype pattern, in particular I would want some way to conviniently redirect method calls to the inner type. Is there a way to do that already ?

I've used delegate before. Or you could implement Deref if applicable in your case.

3 Likes

It depends on your use case. If the proxy is "static" and just delegates to calls to the inner type a macro (or the delegate crate, suggested by @jofas) is probably the best solution. If you want the very dynamic behaviour of a Javascript Proxy, like creating prop values out of thin air, writing custom code is better.

2 Likes

On top of what has already been said, I would add that the recommended way to do this is to implement the AsRef trait when we want to deal with the inner type in the newtype pattern.

4 Likes