Stream: t-compiler

Topic: why can't you use a generic type in a local static?


Jake Goulding (Sep 27 2018 at 23:48, on Zulip):
fn example<T>() {
    static EXAMPLE: Option<T> = None;
}
error[E0401]: can't use type parameters from outer function
 --> src/lib.rs:2:28
  |
1 | fn example<T>() {
  |    ------- - type variable from outer function
  |    |
  |    try adding a local type parameter in this method instead
2 |     static EXAMPLE: Option<T> = None;
  |                            ^ use of type variable from outer function

Ignoring the poor suggestion in the error message, what's the real reason preventing this?

Jake Goulding (Sep 27 2018 at 23:49, on Zulip):

Is it that the compiler doesn't want to (can't?) create N instances of EXAMPLE, one for each concrete instance of T that's used at final compile time?

pnkfelix (Sep 28 2018 at 08:56, on Zulip):

Is it that the compiler doesn't want to (can't?) create N instances of EXAMPLE, one for each concrete instance of T that's used at final compile time?

My suspicion is that the concrete reason what you describe is unsupported is just the more general "we don't let you inherit generics in nested items." I.e. there's no reason per se that we couldn't allow nesting of fn foo<T>(...) { fn bar(x: T) { ... } ... }. But we don't , and that is more of an opinionated design decision...

pnkfelix (Sep 28 2018 at 08:57, on Zulip):

having said that, the hypothesis you put forward is a pretty good description of why the lang team might balk at adding support for allowing local statics in a generic function...

pnkfelix (Sep 28 2018 at 08:58, on Zulip):

(i.e., I'd summarize it as "people expect there to be a single instance of a given static. A generic static inherently breaks that.")

pnkfelix (Sep 28 2018 at 08:59, on Zulip):

also, I don't know if the language itself guarantees that it will always use a monomorphization strategy for implementing all generics...

Last update: Nov 22 2019 at 05:20UTC