Skip to content

Commit 768ad26

Browse files
committed
rpt 36
1 parent 30d56e5 commit 768ad26

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

content/blog/rust-pro-tips-collection.md

+52
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,58 @@ license:
1212

1313
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.
1414

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+
use std::sync::Arc;
25+
26+
struct MyStruct;
27+
28+
impl MyStruct {
29+
fn only_when_wrapped(self: &Arc<Self>) {
30+
println!("I'm in an Arc!");
31+
}
32+
}
33+
34+
let s = 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
55+
|
56+
14 | Arc::new(s).only_when_wrapped();
57+
| +++++++++ +
58+
```
59+
60+
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3c62ee66a4590666ca3aa85070829687) \
61+
[Docs](https://doc.rust-lang.org/reference/items/associated-items.html#methods)
62+
63+
---
64+
65+
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))
66+
1567
## 35. Force compilation failure
1668

1769
[Tweet](https://x.com/sudo_build/status/1791446158055018637) [Toot](https://infosec.exchange/@hatchet/112456435462770019)

0 commit comments

Comments
 (0)