File: type-id-higher-rank-2.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (31 lines) | stat: -rw-r--r-- 798 bytes parent folder | download | duplicates (5)
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
//@ run-pass
// Test that we can't ignore lifetimes by going through Any.

use std::any::Any;

struct Foo<'a>(&'a str);

fn good(s: &String) -> Foo { Foo(s) }

fn bad1(s: String) -> Option<&'static str> {
    let a: Box<dyn Any> = Box::new(good as fn(&String) -> Foo);
    a.downcast_ref::<fn(&String) -> Foo<'static>>().map(|f| f(&s).0)
}

trait AsStr<'a, 'b> {
    fn get(&'a self) -> &'b str;
}

impl<'a> AsStr<'a, 'a> for String {
   fn get(&'a self) -> &'a str { self }
}

fn bad2(s: String) -> Option<&'static str> {
    let a: Box<dyn Any> = Box::new(Box::new(s) as Box<dyn for<'a> AsStr<'a, 'a>>);
    a.downcast_ref::<Box<dyn for<'a> AsStr<'a, 'static>>>().map(|x| x.get())
}

fn main() {
    assert_eq!(bad1(String::from("foo")), None);
    assert_eq!(bad2(String::from("bar")), None);
}