3 ms·
Do you have an example? Copying is only hard to the extent that you need to #[derive(Copy)] for your type, and ints are already Copy. I also don't see how other
by lukebitts 7y ago
Do you have an example? Copying is only hard to the extent that you need to #[derive(Copy)] for your type, and ints are already Copy. I also don't see how other traits factor here.
- weberc2 7y agoIt's been a while, but I tried implementing a trait that took `&self` with several different types. One such type was an integer type, so I had to pass by reference. It's probably not a big deal, but there are many things like this that seem to prefer you move or reference rather than copy. I think it would be better for all traits to implement their methods on `self` and then the caller can choose whether the type that implements the trait is `i64` or `&i64` (instead of the trait being prescriptive about the type, which largely defeats the purpose of traits to begin with). That said, I'm not very experienced in Rust, so I expect someone can correct me about why this is a Very Bad Idea.
- lytigas 7y agoRust 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&edition=2018&gist=f7f9b2a0a956b6b6776452133f5c53fc https://play.rust-lang.org/?version=stable&mode=debug&editio... [1] https://doc.rust-lang.org/std/convert/trait.AsRef.html https://doc.rust-lang.org/std/convert/trait.AsRef.html