@@ -431,36 +431,6 @@ In any case, whatever the lifetime of `r` is, the pointer produced by
431
431
field of a struct is valid as long as the struct is valid. Therefore,
432
432
the compiler accepts the function ` get_x() ` .
433
433
434
- To emphasize this point, let’s look at a variation on the example, this
435
- time one that does not compile:
436
-
437
- ~~~ {.ignore}
438
- struct Point {x: f64, y: f64}
439
- fn get_x_sh(p: &Point) -> &f64 {
440
- &p.x // Error reported here
441
- }
442
- ~~~
443
-
444
- Here, the function ` get_x_sh() ` takes a reference as input and
445
- returns a reference. As before, the lifetime of the reference
446
- that will be returned is a parameter (specified by the
447
- caller). That means that ` get_x_sh() ` promises to return a reference
448
- that is valid for as long as the caller would like: this is
449
- subtly different from the first example, which promised to return a
450
- pointer that was valid for as long as its pointer argument was valid.
451
-
452
- Within ` get_x_sh() ` , we see the expression ` &p.x ` which takes the
453
- address of a field of a Point. The presence of this expression
454
- implies that the compiler must guarantee that , so long as the
455
- resulting pointer is valid, the original Point won't be moved or changed.
456
-
457
- But recall that ` get_x_sh() ` also promised to
458
- return a pointer that was valid for as long as the caller wanted it to
459
- be. Clearly, ` get_x_sh() ` is not in a position to make both of these
460
- guarantees; in fact, it cannot guarantee that the pointer will remain
461
- valid at all once it returns, as the parameter ` p ` may or may not be
462
- live in the caller. Therefore, the compiler will report an error here.
463
-
464
434
In general, if you borrow a struct or box to create a
465
435
reference, it will only be valid within the function
466
436
and cannot be returned. This is why the typical way to return references
0 commit comments