summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_error_codes/src/error_codes/E0746.md
blob: 90755d47f67901188c93af03764be6c1985ab6f7 (plain)
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
An unboxed trait object was used as a return value.

Erroneous code example:

```compile_fail,E0746
trait T {
    fn bar(&self);
}
struct S(usize);
impl T for S {
    fn bar(&self) {}
}

// Having the trait `T` as return type is invalid because
// unboxed trait objects do not have a statically known size:
fn foo() -> dyn T { // error!
    S(42)
}
```

Return types cannot be `dyn Trait`s as they must be `Sized`.

To avoid the error there are a couple of options.

If there is a single type involved, you can use [`impl Trait`]:

```
# trait T {
#     fn bar(&self);
# }
# struct S(usize);
# impl T for S {
#     fn bar(&self) {}
# }
// The compiler will select `S(usize)` as the materialized return type of this
// function, but callers will only know that the return type implements `T`.
fn foo() -> impl T { // ok!
    S(42)
}
```

If there are multiple types involved, the only way you care to interact with
them is through the trait's interface, and having to rely on dynamic dispatch
is acceptable, then you can use [trait objects] with `Box`, or other container
types like `Rc` or `Arc`:

```
# trait T {
#     fn bar(&self);
# }
# struct S(usize);
# impl T for S {
#     fn bar(&self) {}
# }
struct O(&'static str);
impl T for O {
    fn bar(&self) {}
}

// This now returns a "trait object" and callers are only be able to access
// associated items from `T`.
fn foo(x: bool) -> Box<dyn T> { // ok!
    if x {
        Box::new(S(42))
    } else {
        Box::new(O("val"))
    }
}
```

Finally, if you wish to still be able to access the original type, you can
create a new `enum` with a variant for each type:

```
# trait T {
#     fn bar(&self);
# }
# struct S(usize);
# impl T for S {
#     fn bar(&self) {}
# }
# struct O(&'static str);
# impl T for O {
#     fn bar(&self) {}
# }
enum E {
    S(S),
    O(O),
}

// The caller can access the original types directly, but it needs to match on
// the returned `enum E`.
fn foo(x: bool) -> E {
    if x {
        E::S(S(42))
    } else {
        E::O(O("val"))
    }
}
```

You can even implement the `trait` on the returned `enum` so the callers
*don't* have to match on the returned value to invoke the associated items:

```
# trait T {
#     fn bar(&self);
# }
# struct S(usize);
# impl T for S {
#     fn bar(&self) {}
# }
# struct O(&'static str);
# impl T for O {
#     fn bar(&self) {}
# }
# enum E {
#     S(S),
#     O(O),
# }
impl T for E {
    fn bar(&self) {
        match self {
            E::S(s) => s.bar(),
            E::O(o) => o.bar(),
        }
    }
}
```

If you decide to use trait objects, be aware that these rely on
[dynamic dispatch], which has performance implications, as the compiler needs
to emit code that will figure out which method to call *at runtime* instead of
during compilation. Using trait objects we are trading flexibility for
performance.

[`impl Trait`]: https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits
[trait objects]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types
[dynamic dispatch]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch