You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/blog/rust-pro-tips-collection.md
+52
Original file line number
Diff line number
Diff line change
@@ -12,6 +12,58 @@ license:
12
12
13
13
This is a collection of Rust "pro tips" that I've collected, most of which have been [posted on Twitter](https://twitter.com/search?q=%23RustProTip%20%40sudo_build&src=typed_query&f=top). I'll keep updating this post as I write more. Tips are ordered in reverse chronological order, with the most recent ones at the top.
14
14
15
+
## 36. Specify the type of `self` in method signatures
16
+
17
+
<!--
18
+
[Tweet]() [Toot]()
19
+
-->
20
+
21
+
While the three most common types of the `self` parameter have useful shorthands (`self`, `&self`, `&mut self`), the explicit syntax can also include standard library types that deref to `Self`, including `Box<T>`, `Rc<T>`, `Arc<T>`.
22
+
23
+
```rust
24
+
usestd::sync::Arc;
25
+
26
+
structMyStruct;
27
+
28
+
implMyStruct {
29
+
fnonly_when_wrapped(self:&Arc<Self>) {
30
+
println!("I'm in an Arc!");
31
+
}
32
+
}
33
+
34
+
lets=MyStruct;
35
+
// let s = Arc::new(s); // Try uncommenting this line.
36
+
s.only_when_wrapped(); // ERROR!
37
+
```
38
+
39
+
Without wrapping the value in an `Arc`, the Rust compiler produces this error:
40
+
41
+
```text
42
+
error[E0599]: no method named `only_when_wrapped` found for struct `MyStruct` in the current scope
43
+
--> src/main.rs:14:3
44
+
|
45
+
4 | struct MyStruct;
46
+
| --------------- method `only_when_wrapped` not found for this struct
47
+
...
48
+
7 | fn only_when_wrapped(self: &Arc<Self>) {
49
+
| ----------------- the method is available for `Arc<MyStruct>` here
50
+
...
51
+
14 | s.only_when_wrapped();
52
+
| ^^^^^^^^^^^^^^^^^ method not found in `MyStruct`
53
+
|
54
+
help: consider wrapping the receiver expression with the appropriate type
The [`arbitrary_self_types` feature](https://github.com/rust-lang/rfcs/blob/master/text/3519-arbitrary-self-types-v2.md) allows types to implement a new trait `std::ops::Receiver` and appear in the type declaration of `self`. ([tracking issue #44874](https://github.com/rust-lang/rust/issues/44874))
0 commit comments