Use statement in implementation blocks

#1

Hello, I recently discussed on the subreddit[1], why is it not possible to have an use statement inside of the impl block, which would be extremely handy, mainly in enumeration implementations.

For clearance, effect of the use statement would be inside of the implementation block, same as is with the mod block, so imported names would be visible in all methods defined in the implementation block, without contaminating whole module, in which the enumeration is defined:

enum List<T> {
  Cons {
    value: T,
    next: Box<List<T>>,
  },
  Nil,
}

impl<T> List<T> {
  use crate::LinkedList::*;
  
  pub fn empty() -> Self {
    Nil
  }
}

Thanks & Cheers !

[1] https://www.reddit.com/r/rust/comments/axzcmb/why_is_use_statement_not_allowed_in_impl_block/

0 Likes

#2

My apologies, just found out there was an RFC which tried to deal with this, but was ultimately rejected, because of deeper internal problems. There is nice explenation in the subreddit.

Cheers !

1 Like

#3

In the case you really do need to use things at the impl level, you can move that use statement inside of the fn and it should work.

0 Likes

#4

Yes, I am aware, but it would be cool, if you would not had to copy&paste that use statement into all methods defined inside the impl, but rather define single use at the top of impl. Other solution would be putting it into the module, where the impl block is defined, but that would contaminate the whole block with that.

0 Likes

#5

Because it doesn’t matter where you put an impl, you can also just do

mod whatever_it_does_not_matter {
  use super::*;
  use crate::LinkedList::*;
  impl<T> List<T> {  
    pub fn empty() -> Self {
      Nil
    }
  }
}
0 Likes