|
| 1 | +<span class="hljs-keyword">use</span> std::fmt::<span class="hljs-built_in">Debug</span>; <span class="hljs-comment">// Trait to bound with.</span> |
| 2 | + |
| 3 | +<span class="hljs-meta">#[derive(Debug)]</span> |
| 4 | +<span class="hljs-keyword">struct</span> <span class="hljs-title class_">Ref</span><<span class="hljs-symbol">'a</span>, T: <span class="hljs-symbol">'a</span>>(&<span class="hljs-symbol">'a</span> T); |
| 5 | +<span class="hljs-comment">// `Ref` contains a reference to a generic type `T` that has</span> |
| 6 | +<span class="hljs-comment">// some lifetime `'a` unknown by `Ref`. `T` is bounded such that any</span> |
| 7 | +<span class="hljs-comment">// *references* in `T` must outlive `'a`. Additionally, the lifetime</span> |
| 8 | +<span class="hljs-comment">// of `Ref` may not exceed `'a`.</span> |
| 9 | + |
| 10 | +<span class="hljs-comment">// A generic function which prints using the `Debug` trait.</span> |
| 11 | +<span class="hljs-keyword">fn</span> <span class="hljs-title function_">print</span><T>(t: T) <span class="hljs-keyword">where</span> |
| 12 | + T: <span class="hljs-built_in">Debug</span> { |
| 13 | + <span class="hljs-built_in">println!</span>(<span class="hljs-string">"`print`: t is {:?}"</span>, t); |
| 14 | +} |
| 15 | + |
| 16 | +<span class="hljs-comment">// Here a reference to `T` is taken where `T` implements</span> |
| 17 | +<span class="hljs-comment">// `Debug` and all *references* in `T` outlive `'a`. In</span> |
| 18 | +<span class="hljs-comment">// addition, `'a` must outlive the function.</span> |
| 19 | +<span class="hljs-keyword">fn</span> <span class="hljs-title function_">print_ref</span><<span class="hljs-symbol">'a</span>, T>(t: &<span class="hljs-symbol">'a</span> T) <span class="hljs-keyword">where</span> |
| 20 | + T: <span class="hljs-built_in">Debug</span> + <span class="hljs-symbol">'a</span> { |
| 21 | + <span class="hljs-built_in">println!</span>(<span class="hljs-string">"`print_ref`: t is {:?}"</span>, t); |
| 22 | +} |
| 23 | + |
| 24 | +<span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() { |
| 25 | + <span class="hljs-keyword">let</span> <span class="hljs-variable">x</span> = <span class="hljs-number">7</span>; |
| 26 | + <span class="hljs-keyword">let</span> <span class="hljs-variable">ref_x</span> = <span class="hljs-title function_ invoke__">Ref</span>(&x); |
| 27 | + |
| 28 | + <span class="hljs-title function_ invoke__">print_ref</span>(&ref_x); |
| 29 | + <span class="hljs-title function_ invoke__">print</span>(ref_x); |
| 30 | +} |
0 commit comments