-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
847 lines (626 loc) · 12.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
<!DOCTYPE html>
<html>
<head>
<title>Rust syntax conveniences</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<textarea id="source">
class: middle, center
# syntax conveniences afforded by the Rust compiler
Tshepang ~~Lekhonkhobe~~ Mbambo
@tshepang_dev
???
bunch of firsts:
- outside Africa
- software-related conference
- talk
So grateful to whoever took a chance on me to be here,
also because it's been a dream of mine for years to talk to
programming audience,
and it's one of those dreams that feel so distant
(I am a lucky person).
***
There is a constant question about what's the right amount of
convenience.
The answer varies depending on things like experience
(in and outside of Rust).
People can also adapt, but this is also complicated by the desire to
accomodate both new and old users of a tool.
My thought is that "the right amount of convenience" is "something
that makes tedious things less so, without hiding things in a way that
surprises anyone".
This is not what the talk is about... it's more about exploring some
the conveniences by rustc, through the use of examples.
***
I have a fear that somewhere in the slides I got something wrong, and
I would like you to please indicate later on, in any forum or in private.
---
class: middle, left
# about
- I studied electronics formally, but prefer software
- I was a Python fan, and now Rust
- I work at https://panoptix.co.za, which uses Rust in production since 2016
- https://twitter.com/tshepang_dev
???
- enthusiastic boss took a bet on Rust
- not much Rust in Johannesburg, but he looked me up anyways, since I
was sort of active in the ecosystem
- our meetup hasn't been impressive, but just might, since we are
moving it to a a place where it may attract more eyes
---
class: middle, center
count: false
## looping
---
class: middle, center
### desired output
```
1
2
3
```
???
let's say we want code that results in this
---
class: middle, left
raw
```rust
let three = [1, 2, 3];
let count = three.len();
let mut index = 0;
loop {
if index == count {
break;
}
println!("{}", three[index]);
index += 1;
}
```
???
I have come to like Rust syntax, and think the above look good. But
it's still laborious, and error-prone, and we have convenient syntax
to perform the same thing.
---
class: middle, left
with __while__ keyword, which offers a bit of sugar
```rust
let three = [1, 2, 3];
let count = three.len();
let mut index = 0;
while index < count {
println!("{}", three[index]);
index += 1;
}
```
???
... this isn't much of an improvement thugh,
for we just moved the break-out-the-loop decision maker elsewhere
---
class: middle, left
with a trait
```rust
let three = [1, 2, 3];
let mut it = three.iter();
while let Some(member) = it.next() {
println!("{}", member);
}
```
???
much better
---
class: middle, left
with __for__ keyword, moar sugar
```rust
let three = [1, 2, 3];
for member in three.iter() {
println!("{}", member);
}
```
---
class: middle, left
addendum, a functional approach (aka who needs __for__ anyways)
```rust
let three = [1, 2, 3];
three.iter().for_each(|member| println!("{}", member));
```
---
class: middle, center
count: false
## range
---
class: middle, center
### desired output
```
1
2
3
```
???
same as last time
---
class: middle, left
there is a type we can use
```rust
for n in std::ops::RangeInclusive::new(1, 3) {
println!("{}", n);
}
```
???
btw, I so much like inclusive ranges over exclusive one... they are
simply more obvious.
---
class: middle, left
... or we can take advantage of this convenience
```rust
for n in 1..=3 {
println!("{}", n);
}
```
???
it's weird syntax actually, and I actually preferred the ..., but many
complained that it was not visible enough.
---
class: middle, center
count: false
## method calls
---
class: middle, left
A contrived type
```rust
pub struct MaxThree {
counter: usize,
}
impl MaxThree {
pub fn new() -> Self {
Self { counter: 0 }
}
pub fn increase(&mut self) {
if self.counter < 3 {
self.counter += 1;
}
}
pub fn current(&self) -> usize {
self.counter
}
}
```
---
class: middle, center
### desired output
```plain
loop 0: counter=1
loop 1: counter=2
loop 2: counter=3
loop 3: counter=3
loop 4: counter=3
```
???
On the left is iteration steps
---
class: middle, left
very explicit
```rust
let mut max_three = MaxThree::new();
for n in 0..=4 {
MaxThree::increase(&mut max_three); // <- look that
println!(
"loop {}: counter={:?}",
n,
MaxThree::current(&max_three), // <- look that
);
}
```
---
class: middle, left
with explicit borrows
```rust
let mut max_three = MaxThree::new();
for n in 0..=4 {
(&mut max_three).increase(); // <- look that
println!(
"loop {}: counter={:?}",
n,
(&max_three).current(), // <- look that
);
}
```
---
class: middle, left
then, finally...
```rust
let mut max_three = MaxThree::new();
for n in 0..=4 {
max_three.increase();
println!(
"loop {}: counter={:?}",
n,
max_three.current(),
)
}
```
---
class: middle, center
count: false
## Self shorthand
---
class: middle, left
A contrived type (again)
```rust
struct Number(i32);
impl Number {
fn increase(self: &mut Self) {
self.0 += 1;
}
fn increase_elided(&mut self) {
self.0 += 1;
}
}
```
---
class: middle, left
They behave exactly the same
```rust
let mut number = Number(0);
number.increase();
println!("explicit increment: {}", number.0);
number.increase_elided();
println!("elided increment: {}", number.0);
```
output
```
explicit increment: 1
elided increment: 2
```
---
class: middle, left
the whole list
```rust
self ~-> self: Self
&self ~-> self: &Self
&mut self ~-> self: &mut Self
```
with familiar surroundings
```rust
fn foo(self) ~-> fn foo(self: Self)
fn foo(&self) ~-> fn foo(self: &Self)
fn foo(&mut self) ~-> fn foo(self: &mut Self)
```
---
class: middle, center
count: false
## arithmetic shorthands
---
class: middle, left
before
```rust
let mut foo = 1;
foo = foo + 1;
assert_eq!(foo, 2);
```
after
```rust
let mut foo = 1;
foo += 1; // <- look that
assert_eq!(foo, 2);
```
---
class: middle, left
similarly
```rust
let mut foo = 4;
foo = foo * 4;
assert_eq!(foo, 16);
```
after
```rust
let mut foo = 4;
foo *= 4; // <- look that
assert_eq!(foo, 16);
```
---
class: middle, center
count: false
## question mark operator
---
class: middle, left
before
```rust
let content = match fs::read("/etc/os-release") {
Ok(content) => content,
Err(why) => return Err(why),
};
```
after
```rust
let content = fs::read("/etc/os-release")?; // <- look that
```
---
class: middle, left
and now for something nested
```rust
let content_bytes = match fs::read("/etc/motd") {
Ok(content) => content,
Err(why) => return Err(why.into()),
};
let content_utf8 = match String::from_utf8(content_bytes) {
Ok(content) => content,
Err(why) => return Err(why.into()),
};
```
---
class: middle, left
much better...
```rust
let content = String::from_utf8(fs::read("/etc/motd")?)?;
```
???
You may note that this is contrived, since stdlib got
`fs::read_to_string` method.
---
class: middle, center
count: false
## lifetime elision
---
class: middle, left
function call before
```rust
fn not_elided<'a>(value: &'a str) {
println!("{}", value);
}
```
... and after
```rust
fn elided(value: &str) {
println!("{}", value);
}
```
???
this is ugly notation, so it's kool that we don't have to specify it
in obvious cases like one shown here
---
class: middle, left
**const**
```rust
const NOISY: &'static str = "some value";
const ELIDED: &str = "some value"
```
**static**
```rust
static NOISY: &'static str = "some value"
static ELIDED: &str = "some value";
```
---
class: middle, center
count: false
## type inference, and coercion
---
class: middle, left
all bare
```rust
let value: Vec<u8> = (1_u8..=3_u8).collect();
```
less type annotating
```rust
let value: Vec<_> = (1_u8..=3_u8).collect();
```
even less annotating
```rust
let value: Vec<_> = (1_u8..=3).collect();
```
you can also just go with fallback int type, `i32`
```rust
let value: Vec<_> = (1..=3).collect();
```
---
class: middle, left
addendum, something surprising
```rust
let mut value: Vec<_> = (1..=3).collect();
assert_eq!(value, [1, 2, 3_u8]);
value.insert(3, 266);
println!("{:?}", value);
```
???
There are probably use-cases where this behavior is desired, and
perhaps this example it too contrived for the surprise in real code
---
class: middle, left
```
[1, 2, 3, 10]
```
---
class: middle, left
There is also...
```rust
let mut explicit: Vec<f32> = Vec::new();
explicit.push(0.1_f32);
let mut inferred = Vec::new();
inferred.push(0.1_f32);
```
We could also just rely on the float fallback, `f64`
```rust
let mut inferred = Vec::new();
inferred.push(0.1);
```
---
class: middle, left
```rust
// very explicit... no inference or coercion
let foo: i64 = 1_64;
// coerced to i8
let foo: i8 = 1;
// inferred to i16
let foo = 1;
assert_eq!(foo, 1_i16);
// inferred to i32, the int fallback
let foo = 1;
assert_eq!(foo, 1);
```
---
class: middle, left
no type annotation (turbofish) needed on `Iter::collect`
```rust
fn to_vec(value: &str) -> Vec<&str> {
value.split_whitespace().collect()
}
let value = to_vec("1 2 3");
assert_eq!(value, vec!["1", "2", "3"]);
```
... but we could if we wanted
```rust
value.split_whitespace().collect::<Vec<&str>>()
```
---
class: middle, center
count: false
## derive
---
class: middle, left
### ~~desired~~ expected output
```rust
Point {
x: 1,
y: 2
}
```
(I wish there was a trailing comma, for my eyes)
---
class: middle, left
imagine
```rust
use std::fmt;
struct Point {
x: isize,
y: isize,
}
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Point")
.field("x", &self.x)
.field("y", &self.y)
.finish()
}
}
let point = Point { x: 1, y: 2 };
println!("{:#?}", point);
```
???
btw when I looked at fmt module, was amazed by the options that it
offers... that stuff so featureful.
---
class: middle, left
more pleasant
```rust
#[derive(Debug)] // <- look that
struct Point {
x: isize,
y: isize,
}
let point = Point { x: 1, y: 2 };
println!("{:#?}", point);
```
???
This ease also means most people don't need to look at fmt
---
class: middle, center
count: false
## deref coercion
---
class: middle, left
setup
```rust
use std::{
ffi::OsStr,
ops::Deref,
path::{Path, PathBuf},
};
let borrowed = Path::new("some/path.txt");
let owned = PathBuf::from("some/path.txt");
```
---
class: middle, left
we can do all these
```rust
assert_eq!(owned, borrowed);
assert_eq!(&owned, borrowed); // another way to peel avo
assert_eq!(owned, *borrowed); // yet another way to peel avo
```
also
```rust
fn ext(value: &Path) -> Option<&OsStr> {
value.extension()
}
assert_eq!(ext(&owned), ext(borrowed));
assert_eq!(ext(owned.deref()), ext(borrowed));
assert_eq!(ext(owned.as_path()), ext(borrowed));
assert_eq!(ext(&owned), Some(OsStr::new("txt")));
```
---
class: middle, center
count: false
## if let
---
class: middle, left
```rust
let maybe = (1..3).next();
// before
match maybe {
Some(value) => println!("{:?}", value),
None => (),
};
// after
if let Some(value) = maybe {
println!("{:?}", value);
};
```
---
class: middle, center
count: false
## pretty imports
---
class: middle, left
you could do this
```rust
use std::fs;
use std::path;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
```
or this
```rust
use std::{fs, path::{self, Path, PathBuf}, time::Duration};
```
maybe this even
```rust
use std::{
fs,
path::{
self,
Path,
PathBuf,
},
time::Duration,
};
```
???
you saw example of the last style earlier
---
class: middle, left
# thanks
- Rust in Ten Slides (https://github.com/steveklabnik/rust-in-ten-slides)
- RustFest Paris 2018, for inspiration (https://paris.rustfest.eu)
- Rust team (https://rust-lang.org/team)
???
thanks to steved for having a look at a draft, and resulting suggestions
btw, I will be in Rome next month
</textarea>
<script src="remark-latest.min.js" type="text/javascript">
</script>
<script type="text/javascript">
var slideshow = remark.create();
</script>
</body>
</html>