Hacker News new | ask | show | jobs
by lytigas 2493 days ago
Rust basically has this functionality. Whether a type is borrowed or not dictates what I can do with it. For example, I cannot remove items from a `Vec` with a shared &reference. Thus, without knowing which reference type is used in a trait method, I cannot write generic code; I don't know whether my function must take &T or T.

There might be a way around this limitation, but it makes figuring out who is supposed to free a resource hard to do.

The rust solution is to have different traits for different levels of ownership. For example, if I want to iterate over a vector of strings, I can get a Iterator<&str> without destroying the vector. If I'm willing to destroy it, I can get an Iterator<String>.

Or, you can actually implement a trait on a reference type[0] to convert a `self` argument to effectively `&self`. This is the recommended way to implement some conversions, using AsRef and/or Into[1].

[0] https://play.rust-lang.org/?version=stable&mode=debug&editio... [1] https://doc.rust-lang.org/std/convert/trait.AsRef.html