@@ -347,40 +347,50 @@ easiest just to show an example:
347
347
348
348
``` rust
349
349
trait Foo {
350
- fn bar (& self );
350
+ fn is_valid (& self ) -> bool ;
351
351
352
- fn baz (& self ) { println! ( " We called baz. " ); }
352
+ fn is_invalid (& self ) -> bool { ! self . is_valid () }
353
353
}
354
354
```
355
355
356
- Implementors of the ` Foo ` trait need to implement ` bar ()` , but they don’t
357
- need to implement ` baz ()` . They’ll get this default behavior. They can
356
+ Implementors of the ` Foo ` trait need to implement ` is_valid ()` , but they don’t
357
+ need to implement ` is_invalid ()` . They’ll get this default behavior. They can
358
358
override the default if they so choose:
359
359
360
360
``` rust
361
361
# trait Foo {
362
- # fn bar (& self );
363
- # fn baz (& self ) { println! (" We called baz." ); }
362
+ # fn is_valid (& self ) -> bool ;
363
+ #
364
+ # fn is_invalid (& self ) -> bool { ! self . is_valid () }
364
365
# }
365
366
struct UseDefault ;
366
367
367
368
impl Foo for UseDefault {
368
- fn bar (& self ) { println! (" We called bar." ); }
369
+ fn is_valid (& self ) -> bool {
370
+ println! (" Called UseDefault.is_valid." );
371
+ true
372
+ }
369
373
}
370
374
371
375
struct OverrideDefault ;
372
376
373
377
impl Foo for OverrideDefault {
374
- fn bar (& self ) { println! (" We called bar." ); }
378
+ fn is_valid (& self ) -> bool {
379
+ println! (" Called OverrideDefault.is_valid." );
380
+ true
381
+ }
375
382
376
- fn baz (& self ) { println! (" Override baz!" ); }
383
+ fn is_invalid (& self ) -> bool {
384
+ println! (" Called OverrideDefault.is_invalid!" );
385
+ true // this implementation is a self-contradiction!
386
+ }
377
387
}
378
388
379
389
let default = UseDefault ;
380
- default . baz () ; // prints "We called baz ."
390
+ assert! ( ! default . is_invalid ()) ; // prints "Called UseDefault.is_valid ."
381
391
382
392
let over = OverrideDefault ;
383
- over . baz () ; // prints "Override baz !"
393
+ assert! ( over . is_invalid ()) ; // prints "Called OverrideDefault.is_invalid !"
384
394
```
385
395
386
396
# Inheritance
0 commit comments