helix icon indicating copy to clipboard operation
helix copied to clipboard

Consider implicit coercions, e.g. `to_str` for String

Open wagenet opened this issue 7 years ago • 2 comments

For instance, instead of requiring that String values are actually T_STRING we could use implicit coercions (to_str) on the provided object. This would definitely be more Ruby-like in behavior.

Is this something we'd want to do? What are the drawbacks, if any?

wagenet avatar Mar 22 '18 16:03 wagenet

I wrote something like this for Rutie, but rather than using the to_str method call syntax I followed the try_convert design:

  • Array.try_convert
  • Hash.try_convert
  • String.try_convert
  • Regexp.try_convert
  • IO.try_convert

These do an implicit coercion or return a nil object. The trait in that project looks as follows:

pub trait TryConvert<T>: Sized {
    /// The type returned in the event of a conversion error.
    type Nil;

    fn try_convert(value: T) -> Result<Self, Self::Nil>;
}

I like using the Result type with a valid Ruby object in either branch because using the ? operator can allow for a direct return from Rust to Ruby where Rust doesn't have to handle the Result.

In that project I've only implemented this trait for the ruby string type so far. Implicit conversions are more of a rare thing but I believe they're worthwhile.

Hope my input was helpful!

danielpclark avatar Jul 19 '18 02:07 danielpclark

try_convert is also a useful approach, but this sort of use case is literally to_str and friends' raison d'être, so I think the original proposal is a better fit.

crazymykl avatar Sep 12 '18 14:09 crazymykl