rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
8.02k stars 366 forks source link

New idiom: return moved arg on error #336

Closed kriomant closed 1 year ago

simonsan commented 1 year ago

I will give it a proper read on the weekend, first feedback: I think we should prefer "consumed argument" in title over "moved argument". Technically the second is more correct in Rust ownership model, but IMHO the first makes it more clear about what it is for newcomers. Opinions?

kriomant commented 1 year ago

Any feedback?

MarcoIeni commented 1 year ago

I have still this unresolved comment

kriomant commented 1 year ago

I have still this unresolved comment

I put link to Playground there which shows that compilation fails without take.

MarcoIeni commented 1 year ago

I have still this unresolved comment

I put link to Playground there which shows that compilation fails without take.

I don't see the link. Here is the playground without the take.

kriomant commented 1 year ago

Well, and it doesn't compile

Compiling playground v0.0.1 (/playground)
error[[E0308]](https://doc.rust-lang.org/stable/error-index.html#E0308): mismatched types
  --> src/main.rs:18:32
   |
18 |             value = match send(&mut value) {
   |                           ---- ^^^^^^^^^^ expected struct `String`, found `&mut String`
   |                           |
   |                           arguments to this function are incorrect
   |
note: function defined here
  --> src/main.rs:1:8
   |
1  | pub fn send(value: String) -> Result<(), SendError> {
   |        ^^^^ -------------
help: consider removing the borrow
   |
18 -             value = match send(&mut value) {
18 +             value = match send(value) {
   |
MarcoIeni commented 1 year ago

The code from the playground I linked before compiles: image

Can't you follow the compiler advice and remove & mut?

kriomant commented 1 year ago

Can't you follow the compiler advice and remove & mut?

You are right, it's my fault. Fixed example.

MarcoIeni commented 1 year ago

Thanks Mikhail! I merged it 🎉 Simonsan, feel free to open a PR with your suggestions if you give this a read. I merged the PR before your feedback because I think it's very complicated to work with long-lived PRs. I hope you don't mind :)