Use statement in implementation blocks

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/

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

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.

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.

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
    }
  }
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.