Source: add_braces.rs
Adds braces to lambda and match arm expressions.
fn foo(n: i32) -> i32 {
match n {
1 =>┃ n + 1,
_ => 0
}
}
fn foo(n: i32) -> i32 {
match n {
1 => {
n + 1
},
_ => 0
}
}
Source: add_explicit_type.rs
Specify type for a let binding.
fn main() {
let x┃ = 92;
}
fn main() {
let x: i32 = 92;
}
Source: raw_string.rs
Adds a hash to a raw string literal.
fn main() {
r#"Hello,┃ World!"#;
}
fn main() {
r##"Hello, World!"##;
}
Source: add_missing_impl_members.rs
Adds scaffold for overriding default impl members.
trait Trait {
type X;
fn foo(&self);
fn bar(&self) {}
}
impl Trait for () {
type X = ();
fn foo(&self) {}┃
}
trait Trait {
type X;
fn foo(&self);
fn bar(&self) {}
}
impl Trait for () {
type X = ();
fn foo(&self) {}
┃fn bar(&self) {}
}
Source: add_missing_impl_members.rs
Adds scaffold for required impl members.
trait Trait<T> {
type X;
fn foo(&self) -> T;
fn bar(&self) {}
}
impl Trait<u32> for () {┃
}
trait Trait<T> {
type X;
fn foo(&self) -> T;
fn bar(&self) {}
}
impl Trait<u32> for () {
┃type X;
fn foo(&self) -> u32 {
todo!()
}
}
Source: add_label_to_loop.rs
Adds a label to a loop.
fn main() {
loop┃ {
break;
continue;
}
}
fn main() {
'l: loop {
break 'l;
continue 'l;
}
}
Source: add_lifetime_to_type.rs
Adds a new lifetime to a struct, enum or union.
struct Point {
x: &┃u32,
y: u32,
}
struct Point<'a> {
x: &'a u32,
y: u32,
}
Source: add_missing_match_arms.rs
Adds missing clauses to a match
expression.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
┃
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move { distance } => ${1:todo!()},
Action::Stop => ${2:todo!()},┃
}
}
Source: add_return_type.rs
Adds the return type to a function or closure inferred from its tail expression if it doesn’t have a return type specified. This assists is useable in a functions or closures tail expression or return type position.
fn foo() { 4┃2i32 }
fn foo() -> i32 { 42i32 }
Source: add_turbo_fish.rs
Adds ::<_>
to a call of a generic method or function.
fn make<T>() -> T { todo!() }
fn main() {
let x = make┃();
}
fn make<T>() -> T { todo!() }
fn main() {
let x = make::<${0:_}>();
}
Source: apply_demorgan.rs
Apply De Morgan’s law.
This transforms expressions of the form !l || !r
into !(l && r)
.
This also works with &&
. This assist can only be applied with the cursor
on either ||
or &&
.
fn main() {
if x != 4 ||┃ y < 3.14 {}
}
fn main() {
if !(x == 4 && y >= 3.14) {}
}
Source: apply_demorgan.rs
Apply De Morgan’s law to
Iterator::all
and Iterator::any
.
This transforms expressions of the form !iter.any(|x| predicate(x))
into
iter.all(|x| !predicate(x))
and vice versa. This also works the other way for
Iterator::all
into Iterator::any
.
fn main() {
let arr = [1, 2, 3];
if !arr.into_iter().┃any(|num| num == 4) {
println!("foo");
}
}
fn main() {
let arr = [1, 2, 3];
if arr.into_iter().all(|num| num != 4) {
println!("foo");
}
}
Source: auto_import.rs
If the name is unresolved, provides all possible imports for it.
fn main() {
let map = HashMap┃::new();
}
use std::collections::HashMap;
fn main() {
let map = HashMap::new();
}
Source: bind_unused_param.rs
Binds unused function parameter to an underscore.
fn some_function(x: i32┃) {}
fn some_function(x: i32) {
let _ = x;
}
Source: bool_to_enum.rs
This converts boolean local variables, fields, constants, and statics into a new
enum with two variants Bool::True
and Bool::False
, as well as replacing
all assignments with the variants and replacing all usages with == Bool::True
or
== Bool::False
.
fn main() {
let ┃bool = true;
if bool {
println!("foo");
}
}
#[derive(PartialEq, Eq)]
enum Bool { True, False }
fn main() {
let bool = Bool::True;
if bool == Bool::True {
println!("foo");
}
}
Source: change_visibility.rs
Adds or changes existing visibility specifier.
┃fn frobnicate() {}
pub(crate) fn frobnicate() {}
Converts comments to documentation.
// Wow what ┃a nice module
// I sure hope this shows up when I hover over it
//! Wow what a nice module
//! I sure hope this shows up when I hover over it
Source: convert_bool_then.rs
Converts a bool::then
method call to an equivalent if expression.
fn main() {
(0 == 0).then┃(|| val)
}
fn main() {
if 0 == 0 {
Some(val)
} else {
None
}
}
Source: convert_closure_to_fn.rs
This converts a closure to a freestanding function, changing all captures to parameters.
fn main() {
let mut s = String::new();
let closure = |┃a| s.push_str(a);
closure("abc");
}
fn main() {
let mut s = String::new();
fn closure(a: &str, s: &mut String) {
s.push_str(a)
}
closure("abc", &mut s);
}
Source: convert_iter_for_each_to_for.rs
Converts a for loop into a for_each loop on the Iterator.
fn main() {
let x = vec![1, 2, 3];
for┃ v in x {
let y = v * 2;
}
}
fn main() {
let x = vec![1, 2, 3];
x.into_iter().for_each(|v| {
let y = v * 2;
});
}
Source: convert_from_to_tryfrom.rs
Converts a From impl to a TryFrom impl, wrapping returns in Ok
.
impl ┃From<usize> for Thing {
fn from(val: usize) -> Self {
Thing {
b: val.to_string(),
a: val
}
}
}
impl TryFrom<usize> for Thing {
type Error = ${0:()};
fn try_from(val: usize) -> Result<Self, Self::Error> {
Ok(Thing {
b: val.to_string(),
a: val
})
}
}
Source: convert_bool_then.rs
Converts an if expression into a corresponding bool::then
call.
fn main() {
if┃ cond {
Some(val)
} else {
None
}
}
fn main() {
cond.then(|| val)
}
Source: convert_integer_literal.rs
Converts the base of integer literals to other bases.
const _: i32 = 10┃;
const _: i32 = 0b1010;
Source: convert_into_to_from.rs
Converts an Into impl to an equivalent From impl.
impl ┃Into<Thing> for usize {
fn into(self) -> Thing {
Thing {
b: self.to_string(),
a: self
}
}
}
impl From<usize> for Thing {
fn from(val: usize) -> Self {
Thing {
b: val.to_string(),
a: val
}
}
}
Source: convert_iter_for_each_to_for.rs
Converts an Iterator::for_each function into a for loop.
fn main() {
let iter = iter::repeat((9, 2));
iter.for_each┃(|(x, y)| {
println!("x: {}, y: {}", x, y);
});
}
fn main() {
let iter = iter::repeat((9, 2));
for (x, y) in iter {
println!("x: {}, y: {}", x, y);
}
}
Source: convert_let_else_to_match.rs
Converts let-else statement to let statement and match expression.
fn main() {
let Ok(mut x) = f() else┃ { return };
}
fn main() {
let mut x = match f() {
Ok(x) => x,
_ => return,
};
}
Source: convert_match_to_let_else.rs
Converts let statement with match initializer to let-else statement.
fn foo(opt: Option<()>) {
let val┃ = match opt {
Some(it) => it,
None => return,
};
}
fn foo(opt: Option<()>) {
let Some(val) = opt else { return };
}
Converts struct with named fields to tuple struct, and analogously for enum variants with named fields.
struct Point┃ { x: f32, y: f32 }
impl Point {
pub fn new(x: f32, y: f32) -> Self {
Point { x, y }
}
pub fn x(&self) -> f32 {
self.x
}
pub fn y(&self) -> f32 {
self.y
}
}
struct Point(f32, f32);
impl Point {
pub fn new(x: f32, y: f32) -> Self {
Point(x, y)
}
pub fn x(&self) -> f32 {
self.0
}
pub fn y(&self) -> f32 {
self.1
}
}
Converts a function that is defined within the body of another function into a closure.
fn main() {
fn fo┃o(label: &str, number: u64) {
println!("{}: {}", label, number);
}
foo("Bar", 100);
}
fn main() {
let foo = |label: &str, number: u64| {
println!("{}: {}", label, number);
};
foo("Bar", 100);
}
Source: convert_to_guarded_return.rs
Replace a large conditional with a guarded return.
fn main() {
┃if cond {
foo();
bar();
}
}
fn main() {
if !cond {
return;
}
foo();
bar();
}
This converts the return type of a function from a tuple type into a tuple struct and updates the body accordingly.
fn bar() {
let (a, b, c) = foo();
}
fn foo() -> (┃u32, u32, u32) {
(1, 2, 3)
}
fn bar() {
let FooResult(a, b, c) = foo();
}
struct FooResult(u32, u32, u32);
fn foo() -> FooResult {
FooResult(1, 2, 3)
}
Converts tuple struct to struct with named fields, and analogously for tuple enum variants.
struct Point┃(f32, f32);
impl Point {
pub fn new(x: f32, y: f32) -> Self {
Point(x, y)
}
pub fn x(&self) -> f32 {
self.0
}
pub fn y(&self) -> f32 {
self.1
}
}
struct Point { field1: f32, field2: f32 }
impl Point {
pub fn new(x: f32, y: f32) -> Self {
Point { field1: x, field2: y }
}
pub fn x(&self) -> f32 {
self.field1
}
pub fn y(&self) -> f32 {
self.field2
}
}
Convert 2-arm match that evaluates to a boolean into the equivalent matches! invocation.
fn main() {
match scrutinee┃ {
Some(val) if val.cond() => true,
_ => false,
}
}
fn main() {
matches!(scrutinee, Some(val) if val.cond())
}
Source: convert_while_to_loop.rs
Replace a while with a loop.
fn main() {
┃while cond {
foo();
}
}
fn main() {
loop {
if !cond {
break;
}
foo();
}
}
Source: destructure_struct_binding.rs
Destructures a struct binding in place.
struct Foo {
bar: i32,
baz: i32,
}
fn main() {
let ┃foo = Foo { bar: 1, baz: 2 };
let bar2 = foo.bar;
let baz2 = &foo.baz;
}
struct Foo {
bar: i32,
baz: i32,
}
fn main() {
let Foo { bar, baz } = Foo { bar: 1, baz: 2 };
let bar2 = bar;
let baz2 = &baz;
}
Source: destructure_tuple_binding.rs
Destructures a tuple binding in place.
fn main() {
let ┃t = (1,2);
let v = t.0;
}
fn main() {
let (┃_0, _1) = (1,2);
let v = _0;
}
Source: toggle_async_sugar.rs
Rewrites asynchronous function from async fn
into → impl Future
.
This action does not touch the function body and therefore 0
block does not transform to async { 0 }
.
pub as┃ync fn foo() -> usize {
0
}
pub fn foo() -> impl core::future::Future<Output = usize> {
0
}
Source: desugar_doc_comment.rs
Desugars doc-comments to the attribute form.
/// Multi-line┃
/// comment
#[doc = r"Multi-line
comment"]
Source: expand_glob_import.rs
Expands glob imports.
mod foo {
pub struct Bar;
pub struct Baz;
}
use foo::*┃;
fn qux(bar: Bar, baz: Baz) {}
mod foo {
pub struct Bar;
pub struct Baz;
}
use foo::{Bar, Baz};
fn qux(bar: Bar, baz: Baz) {}
Source: explicit_enum_discriminant.rs
Adds explicit discriminant to all enum variants.
enum TheEnum┃ {
Foo,
Bar,
Baz = 42,
Quux,
}
enum TheEnum {
Foo = 0,
Bar = 1,
Baz = 42,
Quux = 43,
}
Source: extract_variable.rs
Extracts subexpression into a constant.
fn main() {
┃(1 + 2)┃ * 4;
}
fn main() {
const ┃VAR_NAME: i32 = 1 + 2;
VAR_NAME * 4;
}
Move an expression out of a format string.
fn main() {
print!("{var} {x + 1}┃");
}
fn main() {
print!("{var} {}"┃, x + 1);
}
Source: extract_function.rs
Extracts selected statements and comments into new function.
fn main() {
let n = 1;
┃let m = n + 2;
// calculate
let k = m + n;┃
let g = 3;
}
fn main() {
let n = 1;
fun_name(n);
let g = 3;
}
fn ┃fun_name(n: i32) {
let m = n + 2;
// calculate
let k = m + n;
}
Source: extract_module.rs
Extracts a selected region as separate module. All the references, visibility and imports are resolved.
┃fn foo(name: i32) -> i32 {
name + 1
}┃
fn bar(name: i32) -> i32 {
name + 2
}
mod modname {
pub(crate) fn foo(name: i32) -> i32 {
name + 1
}
}
fn bar(name: i32) -> i32 {
name + 2
}
Source: extract_variable.rs
Extracts subexpression into a static.
fn main() {
┃(1 + 2)┃ * 4;
}
fn main() {
static ┃VAR_NAME: i32 = 1 + 2;
VAR_NAME * 4;
}
Extracts a struct from enum variant.
enum A { ┃One(u32, u32) }
struct One(u32, u32);
enum A { One(One) }
Source: extract_type_alias.rs
Extracts the selected type as a type alias.
struct S {
field: ┃(u8, u8, u8)┃,
}
type ┃Type = (u8, u8, u8);
struct S {
field: Type,
}
Source: extract_variable.rs
Extracts subexpression into a variable.
fn main() {
┃(1 + 2)┃ * 4;
}
fn main() {
let ┃var_name = 1 + 2;
var_name * 4;
}
Source: fill_record_pattern_fields.rs
Fills fields by replacing rest pattern in record patterns.
struct Bar { y: Y, z: Z }
fn foo(bar: Bar) {
let Bar { ..┃ } = bar;
}
struct Bar { y: Y, z: Z }
fn foo(bar: Bar) {
let Bar { y, z } = bar;
}
Source: fix_visibility.rs
Makes inaccessible item public.
mod m {
fn frobnicate() {}
}
fn main() {
m::frobnicate┃();
}
mod m {
┃pub(crate) fn frobnicate() {}
}
fn main() {
m::frobnicate();
}
Source: flip_binexpr.rs
Flips operands of a binary expression.
fn main() {
let _ = 90 +┃ 2;
}
fn main() {
let _ = 2 + 90;
}
Source: flip_comma.rs
Flips two comma-separated items.
fn main() {
((1, 2),┃ (3, 4));
}
fn main() {
((3, 4), (1, 2));
}
Source: flip_trait_bound.rs
Flips two trait bounds.
fn foo<T: Clone +┃ Copy>() { }
fn foo<T: Copy + Clone>() { }
Source: generate_constant.rs
Generate a named constant.
struct S { i: usize }
impl S { pub fn new(n: usize) {} }
fn main() {
let v = S::new(CAPA┃CITY);
}
struct S { i: usize }
impl S { pub fn new(n: usize) {} }
fn main() {
const CAPACITY: usize = ┃;
let v = S::new(CAPACITY);
}
Adds a Default impl for an enum using a variant.
enum Version {
Undefined,
Minor┃,
Major,
}
enum Version {
Undefined,
Minor,
Major,
}
impl Default for Version {
fn default() -> Self {
Self::Minor
}
}
Source: generate_default_from_new.rs
Generates default implementation from new method.
struct Example { _inner: () }
impl Example {
pub fn n┃ew() -> Self {
Self { _inner: () }
}
}
struct Example { _inner: () }
impl Example {
pub fn new() -> Self {
Self { _inner: () }
}
}
impl Default for Example {
fn default() -> Self {
Self::new()
}
}
Source: generate_delegate_methods.rs
Generate delegate methods.
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
ag┃e: Age,
}
struct Age(u8);
impl Age {
fn age(&self) -> u8 {
self.0
}
}
struct Person {
age: Age,
}
impl Person {
┃fn age(&self) -> u8 {
self.age.age()
}
}
Source: generate_delegate_trait.rs
Generate delegate trait implementation for `StructField`s.
trait SomeTrait {
type T;
fn fn_(arg: u32) -> u32;
fn method_(&mut self) -> bool;
}
struct A;
impl SomeTrait for A {
type T = u32;
fn fn_(arg: u32) -> u32 {
42
}
fn method_(&mut self) -> bool {
false
}
}
struct B {
a┃: A,
}
trait SomeTrait {
type T;
fn fn_(arg: u32) -> u32;
fn method_(&mut self) -> bool;
}
struct A;
impl SomeTrait for A {
type T = u32;
fn fn_(arg: u32) -> u32 {
42
}
fn method_(&mut self) -> bool {
false
}
}
struct B {
a: A,
}
impl SomeTrait for B {
type T = <A as SomeTrait>::T;
fn fn_(arg: u32) -> u32 {
<A as SomeTrait>::fn_(arg)
}
fn method_(&mut self) -> bool {
<A as SomeTrait>::method_(&mut self.a)
}
}
Source: generate_deref.rs
Generate Deref
impl using the given struct field.
struct A;
struct B {
┃a: A
}
struct A;
struct B {
a: A
}
impl core::ops::Deref for B {
type Target = A;
fn deref(&self) -> &Self::Target {
&self.a
}
}
Source: generate_derive.rs
Adds a new #[derive()]
clause to a struct or enum.
struct Point {
x: u32,
y: u32,┃
}
#[derive(┃)]
struct Point {
x: u32,
y: u32,
}
Generates a rustdoc example when editing an item’s documentation.
/// Adds two numbers.┃
pub fn add(a: i32, b: i32) -> i32 { a + b }
/// Adds two numbers.
///
/// # Examples
///
/// ```
/// use ra_test_fixture::add;
///
/// assert_eq!(add(a, b), );
/// ```
pub fn add(a: i32, b: i32) -> i32 { a + b }
Adds a documentation template above a function definition / declaration.
pub struct S;
impl S {
pub unsafe fn set_len┃(&mut self, len: usize) -> Result<(), std::io::Error> {
/* ... */
}
}
pub struct S;
impl S {
/// Sets the length of this [`S`].
///
/// # Errors
///
/// This function will return an error if .
///
/// # Safety
///
/// .
pub unsafe fn set_len(&mut self, len: usize) -> Result<(), std::io::Error> {
/* ... */
}
}
Generate an as_
method for this enum variant.
enum Value {
Number(i32),
Text(String)┃,
}
enum Value {
Number(i32),
Text(String),
}
impl Value {
fn as_text(&self) -> Option<&String> {
if let Self::Text(v) = self {
Some(v)
} else {
None
}
}
}
Source: generate_enum_is_method.rs
Generate an is_
method for this enum variant.
enum Version {
Undefined,
Minor┃,
Major,
}
enum Version {
Undefined,
Minor,
Major,
}
impl Version {
/// Returns `true` if the version is [`Minor`].
///
/// [`Minor`]: Version::Minor
#[must_use]
fn is_minor(&self) -> bool {
matches!(self, Self::Minor)
}
}
Generate a try_into_
method for this enum variant.
enum Value {
Number(i32),
Text(String)┃,
}
enum Value {
Number(i32),
Text(String),
}
impl Value {
fn try_into_text(self) -> Result<String, Self> {
if let Self::Text(v) = self {
Ok(v)
} else {
Err(self)
}
}
}
Source: generate_enum_variant.rs
Adds a variant to an enum.
enum Countries {
Ghana,
}
fn main() {
let country = Countries::Lesotho┃;
}
enum Countries {
Ghana,
Lesotho,
}
fn main() {
let country = Countries::Lesotho;
}
Source: generate_fn_type_alias.rs
Generate a type alias for the function with named parameters.
unsafe fn fo┃o(n: i32) -> i32 { 42i32 }
type ${0:FooFn} = unsafe fn(n: i32) -> i32;
unsafe fn foo(n: i32) -> i32 { 42i32 }
Source: generate_fn_type_alias.rs
Generate a type alias for the function with unnamed parameters.
unsafe fn fo┃o(n: i32) -> i32 { 42i32 }
type ${0:FooFn} = unsafe fn(i32) -> i32;
unsafe fn foo(n: i32) -> i32 { 42i32 }
Source: generate_from_impl_for_enum.rs
Adds a From impl for this enum variant with one tuple field.
enum A { ┃One(u32) }
enum A { One(u32) }
impl From<u32> for A {
fn from(v: u32) -> Self {
Self::One(v)
}
}
Source: generate_function.rs
Adds a stub function with a signature matching the function under the cursor.
struct Baz;
fn baz() -> Baz { Baz }
fn foo() {
bar┃("", baz());
}
struct Baz;
fn baz() -> Baz { Baz }
fn foo() {
bar("", baz());
}
fn bar(arg: &str, baz: Baz) ${0:-> _} {
todo!()
}
Source: generate_getter_or_setter.rs
Generate a getter method.
struct Person {
nam┃e: String,
}
struct Person {
name: String,
}
impl Person {
fn ┃name(&self) -> &str {
&self.name
}
}
Source: generate_getter_or_setter.rs
Generate a mut getter method.
struct Person {
nam┃e: String,
}
struct Person {
name: String,
}
impl Person {
fn ┃name_mut(&mut self) -> &mut String {
&mut self.name
}
}
Source: generate_impl.rs
Adds a new inherent impl for a type.
struct Ctx┃<T: Clone> {
data: T,
}
struct Ctx<T: Clone> {
data: T,
}
impl<T: Clone> Ctx<T> {┃}
Source: generate_is_empty_from_len.rs
Generates is_empty implementation from the len method.
struct MyStruct { data: Vec<String> }
impl MyStruct {
#[must_use]
p┃ub fn len(&self) -> usize {
self.data.len()
}
}
struct MyStruct { data: Vec<String> }
impl MyStruct {
#[must_use]
pub fn len(&self) -> usize {
self.data.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
Source: generate_mut_trait_impl.rs
Adds a IndexMut impl from the Index
trait.
pub enum Axis { X = 0, Y = 1, Z = 2 }
impl<T> core::ops::Index┃<Axis> for [T; 3] {
type Output = T;
fn index(&self, index: Axis) -> &Self::Output {
&self[index as usize]
}
}
pub enum Axis { X = 0, Y = 1, Z = 2 }
┃impl<T> core::ops::IndexMut<Axis> for [T; 3] {
fn index_mut(&mut self, index: Axis) -> &mut Self::Output {
&self[index as usize]
}
}
impl<T> core::ops::Index<Axis> for [T; 3] {
type Output = T;
fn index(&self, index: Axis) -> &Self::Output {
&self[index as usize]
}
}
Source: generate_new.rs
Adds a fn new
for a type.
struct Ctx<T: Clone> {
data: T,┃
}
struct Ctx<T: Clone> {
data: T,
}
impl<T: Clone> Ctx<T> {
fn ┃new(data: T) -> Self {
Self { data }
}
}
Source: generate_getter_or_setter.rs
Generate a setter method.
struct Person {
nam┃e: String,
}
struct Person {
name: String,
}
impl Person {
fn ┃set_name(&mut self, name: String) {
self.name = name;
}
}
Source: generate_trait_from_impl.rs
Generate trait for an already defined inherent impl and convert impl to a trait impl.
struct Foo<const N: usize>([i32; N]);
macro_rules! const_maker {
($t:ty, $v:tt) => {
const CONST: $t = $v;
};
}
impl<const N: usize> Fo┃o<N> {
// Used as an associated constant.
const CONST_ASSOC: usize = N * 4;
fn create() -> Option<()> {
Some(())
}
const_maker! {i32, 7}
}
struct Foo<const N: usize>([i32; N]);
macro_rules! const_maker {
($t:ty, $v:tt) => {
const CONST: $t = $v;
};
}
trait ${0:NewTrait}<const N: usize> {
// Used as an associated constant.
const CONST_ASSOC: usize = N * 4;
fn create() -> Option<()>;
const_maker! {i32, 7}
}
impl<const N: usize> ${0:NewTrait}<N> for Foo<N> {
// Used as an associated constant.
const CONST_ASSOC: usize = N * 4;
fn create() -> Option<()> {
Some(())
}
const_maker! {i32, 7}
}
Source: generate_impl.rs
Adds a new trait impl for a type.
struct ┃Ctx<T: Clone> {
data: T,
}
struct Ctx<T: Clone> {
data: T,
}
impl<T: Clone> ${0:_} for Ctx<T> {}
Source: inline_call.rs
Inlines a function or method body creating a let
statement per parameter unless the parameter
can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
or if the parameter is only accessed inside the function body once.
fn foo(name: Option<&str>) {
let name = name.unwrap┃();
}
fn foo(name: Option<&str>) {
let name = match name {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),
};
}
Source: inline_const_as_literal.rs
Evaluate and inline const variable as literal.
const STRING: &str = "Hello, World!";
fn something() -> &'static str {
STRING┃
}
const STRING: &str = "Hello, World!";
fn something() -> &'static str {
"Hello, World!"
}
Source: inline_call.rs
Inline a function or method body into all of its callers where possible, creating a let
statement per parameter
unless the parameter can be inlined. The parameter will be inlined either if it the supplied argument is a simple local
or if the parameter is only accessed inside the function body once.
If all calls can be inlined the function will be removed.
fn print(_: &str) {}
fn foo┃(word: &str) {
if !word.is_empty() {
print(word);
}
}
fn bar() {
foo("안녕하세요");
foo("여러분");
}
fn print(_: &str) {}
fn bar() {
{
let word: &str = "안녕하세요";
if !word.is_empty() {
print(word);
}
};
{
let word: &str = "여러분";
if !word.is_empty() {
print(word);
}
};
}
Source: inline_local_variable.rs
Inlines a local variable.
fn main() {
let x┃ = 1 + 2;
x * 4;
}
fn main() {
(1 + 2) * 4;
}
Source: inline_macro.rs
Takes a macro and inlines it one step.
macro_rules! num {
(+$($t:tt)+) => (1 + num!($($t )+));
(-$($t:tt)+) => (-1 + num!($($t )+));
(+) => (1);
(-) => (-1);
}
fn main() {
let number = num┃!(+ + + - + +);
println!("{number}");
}
macro_rules! num {
(+$($t:tt)+) => (1 + num!($($t )+));
(-$($t:tt)+) => (-1 + num!($($t )+));
(+) => (1);
(-) => (-1);
}
fn main() {
let number = 1+num!(+ + - + +);
println!("{number}");
}
Source: inline_type_alias.rs
Replace a type alias with its concrete type.
type A<T = u32> = Vec<T>;
fn main() {
let a: ┃A;
}
type A<T = u32> = Vec<T>;
fn main() {
let a: Vec<u32>;
}
Source: inline_type_alias.rs
Inline a type alias into all of its uses where possible.
type ┃A = i32;
fn id(x: A) -> A {
x
};
fn foo() {
let _: A = 3;
}
fn id(x: i32) -> i32 {
x
};
fn foo() {
let _: i32 = 3;
}
Source: into_to_qualified_from.rs
Convert an into
method call to a fully qualified from
call.
//- minicore: from
struct B;
impl From<i32> for B {
fn from(a: i32) -> Self {
B
}
}
fn main() -> () {
let a = 3;
let b: B = a.in┃to();
}
struct B;
impl From<i32> for B {
fn from(a: i32) -> Self {
B
}
}
fn main() -> () {
let a = 3;
let b: B = B::from(a);
}
Source: introduce_named_generic.rs
Replaces impl Trait
function argument with the named generic.
fn foo(bar: ┃impl Bar) {}
fn foo<┃B: Bar>(bar: B) {}
Source: introduce_named_lifetime.rs
Change an anonymous lifetime to a named lifetime.
impl Cursor<'_┃> {
fn node(self) -> &SyntaxNode {
match self {
Cursor::Replace(node) | Cursor::Before(node) => node,
}
}
}
impl<'a> Cursor<'a> {
fn node(self) -> &SyntaxNode {
match self {
Cursor::Replace(node) | Cursor::Before(node) => node,
}
}
}
Source: invert_if.rs
This transforms if expressions of the form if !x {A} else {B}
into if x {B} else {A}
This also works with !=
. This assist can only be applied with the cursor on if
.
fn main() {
if┃ !y { A } else { B }
}
fn main() {
if y { B } else { A }
}
Source: convert_comment_block.rs
Converts comments between block and single-line form.
// Multi-line┃
// comment
/*
Multi-line
comment
*/
Source: raw_string.rs
Adds r#
to a plain string literal.
fn main() {
"Hello,┃ World!";
}
fn main() {
r#"Hello, World!"#;
}
Source: raw_string.rs
Turns a raw string into a plain string.
fn main() {
r#"Hello,┃ "World!""#;
}
fn main() {
"Hello, \"World!\"";
}
Source: merge_imports.rs
Merges neighbor imports with a common prefix.
use std::┃fmt::Formatter;
use std::io;
use std::{fmt::Formatter, io};
Source: merge_match_arms.rs
Merges the current match arm with the following if their bodies are identical.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
┃Action::Move(..) => foo(),
Action::Stop => foo(),
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move(..) | Action::Stop => foo(),
}
}
Source: merge_nested_if.rs
This transforms if expressions of the form if x { if y {A} }
into if x && y {A}
This assist can only be applied with the cursor on if
.
fn main() {
i┃f x == 3 { if y == 4 { 1 } }
}
fn main() {
if x == 3 && y == 4 { 1 }
}
Source: move_guard.rs
Moves if expression from match arm body into a guard.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move { distance } => ┃if distance > 10 { foo() },
_ => (),
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move { distance } if distance > 10 => foo(),
_ => (),
}
}
Source: move_bounds.rs
Moves inline type bounds to a where clause.
fn apply<T, U, ┃F: FnOnce(T) -> U>(f: F, x: T) -> U {
f(x)
}
fn apply<T, U, F>(f: F, x: T) -> U where F: FnOnce(T) -> U {
f(x)
}
Source: move_const_to_impl.rs
Move a local constant item in a method to impl’s associated constant. All the references will be
qualified with Self::
.
struct S;
impl S {
fn foo() -> usize {
/// The answer.
const C┃: usize = 42;
C * C
}
}
struct S;
impl S {
/// The answer.
const C: usize = 42;
fn foo() -> usize {
Self::C * Self::C
}
}
Source: move_from_mod_rs.rs
Moves xxx/mod.rs to xxx.rs.
//- /main.rs
mod a;
//- /a/mod.rs
┃fn t() {}┃
fn t() {}
Source: move_guard.rs
Moves match guard into match arm body.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move { distance } ┃if distance > 10 => foo(),
_ => (),
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move { distance } => if distance > 10 {
foo()
},
_ => (),
}
}
Source: move_module_to_file.rs
Moves inline module’s contents to a separate file.
mod ┃foo {
fn t() {}
}
mod foo;
Source: move_to_mod_rs.rs
Moves xxx.rs to xxx/mod.rs.
//- /main.rs
mod a;
//- /a.rs
┃fn t() {}┃
fn t() {}
Source: normalize_import.rs
Normalizes an import.
use┃ std::{io, {fmt::Formatter}};
use std::{fmt::Formatter, io};
Source: promote_local_to_const.rs
Promotes a local variable to a const item changing its name to a SCREAMING_SNAKE_CASE
variant
if the local uses no non-const expressions.
fn main() {
let foo┃ = true;
if foo {
println!("It's true");
} else {
println!("It's false");
}
}
fn main() {
const ┃FOO: bool = true;
if FOO {
println!("It's true");
} else {
println!("It's false");
}
}
Source: pull_assignment_up.rs
Extracts variable assignment to outside an if or match statement.
fn main() {
let mut foo = 6;
if true {
┃foo = 5;
} else {
foo = 4;
}
}
fn main() {
let mut foo = 6;
foo = if true {
5
} else {
4
};
}
Source: qualify_method_call.rs
Replaces the method call with a qualified function call.
struct Foo;
impl Foo {
fn foo(&self) {}
}
fn main() {
let foo = Foo;
foo.fo┃o();
}
struct Foo;
impl Foo {
fn foo(&self) {}
}
fn main() {
let foo = Foo;
Foo::foo(&foo);
}
Source: qualify_path.rs
If the name is unresolved, provides all possible qualified paths for it.
fn main() {
let map = HashMap┃::new();
}
fn main() {
let map = std::collections::HashMap::new();
}
Source: number_representation.rs
Adds or removes separators from integer literal.
const _: i32 = 1012345┃;
const _: i32 = 1_012_345;
Source: remove_dbg.rs
Removes dbg!()
macro call.
fn main() {
let x = ┃dbg!(42 * dbg!(4 + 2));┃
}
fn main() {
let x = 42 * (4 + 2);
}
Source: raw_string.rs
Removes a hash from a raw string literal.
fn main() {
r#"Hello,┃ World!"#;
}
fn main() {
r"Hello, World!";
}
Source: remove_mut.rs
Removes the mut
keyword.
impl Walrus {
fn feed(&mut┃ self, amount: u32) {}
}
impl Walrus {
fn feed(&self, amount: u32) {}
}
Source: remove_parentheses.rs
Removes redundant parentheses.
fn main() {
_ = ┃(2) + 2;
}
fn main() {
_ = 2 + 2;
}
Source: remove_unused_imports.rs
Removes any use statements in the current selection that are unused.
struct X();
mod foo {
use super::X┃;
}
struct X();
mod foo {
}
Source: remove_unused_param.rs
Removes unused function parameter.
fn frobnicate(x: i32┃) {}
fn main() {
frobnicate(92);
}
fn frobnicate() {}
fn main() {
frobnicate();
}
Source: reorder_fields.rs
Reorder the fields of record literals and record patterns in the same order as in the definition.
struct Foo {foo: i32, bar: i32};
const test: Foo = ┃Foo {bar: 0, foo: 1}
struct Foo {foo: i32, bar: i32};
const test: Foo = Foo {foo: 1, bar: 0}
Source: reorder_impl_items.rs
Reorder the items of an impl Trait
. The items will be ordered
in the same order as in the trait definition.
trait Foo {
type A;
const B: u8;
fn c();
}
struct Bar;
┃impl Foo for Bar┃ {
const B: u8 = 17;
fn c() {}
type A = String;
}
trait Foo {
type A;
const B: u8;
fn c();
}
struct Bar;
impl Foo for Bar {
type A = String;
const B: u8 = 17;
fn c() {}
}
Source: replace_arith_op.rs
Replaces arithmetic on integers with the checked_*
equivalent.
fn main() {
let x = 1 ┃+ 2;
}
fn main() {
let x = 1.checked_add(2);
}
Source: replace_arith_op.rs
Replaces arithmetic on integers with the saturating_*
equivalent.
fn main() {
let x = 1 ┃+ 2;
}
fn main() {
let x = 1.saturating_add(2);
}
Source: replace_arith_op.rs
Replaces arithmetic on integers with the wrapping_*
equivalent.
fn main() {
let x = 1 ┃+ 2;
}
fn main() {
let x = 1.wrapping_add(2);
}
Source: replace_string_with_char.rs
Replace a char literal with a string literal.
fn main() {
find('{┃');
}
fn main() {
find("{");
}
Converts a derive
impl into a manual one.
#[derive(Deb┃ug, Display)]
struct S;
#[derive(Display)]
struct S;
impl Debug for S {
┃fn fmt(&self, f: &mut Formatter) -> Result<()> {
f.debug_struct("S").finish()
}
}
Source: replace_if_let_with_match.rs
Replaces a if let
expression with a match
expression.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
┃if let Action::Move { distance } = action {
foo(distance)
} else {
bar()
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move { distance } => foo(distance),
_ => bar(),
}
}
Replace if x.is_some()
with if let Some(_tmp) = x
or if x.is_ok()
with if let Ok(_tmp) = x
.
fn main() {
let x = Some(1);
if x.is_som┃e() {}
}
fn main() {
let x = Some(1);
if let Some(${0:x}) = x {}
}
Source: replace_let_with_if_let.rs
Replaces let
with an if let
.
fn main(action: Action) {
┃let x = compute();
}
fn compute() -> Option<i32> { None }
fn main(action: Action) {
if let Some(x) = compute() {
}
}
fn compute() -> Option<i32> { None }
Source: replace_if_let_with_match.rs
Replaces a binary match
with a wildcard pattern and no guards with an if let
expression.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
┃match action {
Action::Move { distance } => foo(distance),
_ => bar(),
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
if let Action::Move { distance } = action {
foo(distance)
} else {
bar()
}
}
Replaces named generic with an impl Trait
in function argument.
fn new<P┃: AsRef<Path>>(location: P) -> Self {}
fn new(location: impl AsRef<Path>) -> Self {}
Adds a use statement for a given fully-qualified name.
fn process(map: std::collections::┃HashMap<String, String>) {}
use std::collections::HashMap;
fn process(map: HashMap<String, String>) {}
Source: replace_string_with_char.rs
Replace string literal with char literal.
fn main() {
find("{┃");
}
fn main() {
find('{');
}
Source: replace_try_expr_with_match.rs
Replaces a try
expression with a match
expression.
fn handle() {
let pat = Some(true)┃?;
}
fn handle() {
let pat = match Some(true) {
Some(it) => it,
None => return None,
};
}
Converts ::<_>
to an explicit type assignment.
fn make<T>() -> T { ) }
fn main() {
let a = make┃::<i32>();
}
fn make<T>() -> T { ) }
fn main() {
let a: i32 = make();
}
Source: replace_method_eager_lazy.rs
Replace unwrap_or_else
with unwrap_or
and ok_or_else
with ok_or
.
fn foo() {
let a = Some(1);
a.unwra┃p_or_else(|| 2);
}
fn foo() {
let a = Some(1);
a.unwrap_or(2);
}
Source: replace_method_eager_lazy.rs
Replace unwrap_or
with unwrap_or_else
and ok_or
with ok_or_else
.
fn foo() {
let a = Some(1);
a.unwra┃p_or(2);
}
fn foo() {
let a = Some(1);
a.unwrap_or_else(|| 2);
}
Source: sort_items.rs
Sorts item members alphabetically: fields, enum variants and methods.
struct ┃Foo┃ { second: u32, first: String }
struct Foo { first: String, second: u32 }
trait ┃Bar┃ {
fn second(&self) -> u32;
fn first(&self) -> String;
}
trait Bar {
fn first(&self) -> String;
fn second(&self) -> u32;
}
struct Baz;
impl ┃Baz┃ {
fn second(&self) -> u32;
fn first(&self) -> String;
}
struct Baz;
impl Baz {
fn first(&self) -> String;
fn second(&self) -> u32;
}
There is a difference between sorting enum variants:
enum ┃Animal┃ {
Dog(String, f64),
Cat { weight: f64, name: String },
}
enum Animal {
Cat { weight: f64, name: String },
Dog(String, f64),
}
and sorting a single enum struct variant:
enum Animal {
Dog(String, f64),
Cat ┃{ weight: f64, name: String }┃,
}
enum Animal {
Dog(String, f64),
Cat { name: String, weight: f64 },
}
Source: split_import.rs
Wraps the tail of import into braces.
use std::┃collections::HashMap;
use std::{collections::HashMap};
Source: toggle_async_sugar.rs
Rewrites asynchronous function from → impl Future
into async fn
.
This action does not touch the function body and therefore async { 0 }
block does not transform to just 0
.
pub fn foo() -> impl core::future::F┃uture<Output = usize> {
async { 0 }
}
pub async fn foo() -> usize {
async { 0 }
}
Source: toggle_ignore.rs
Adds #[ignore]
attribute to the test.
┃#[test]
fn arithmetics {
assert_eq!(2 + 2, 5);
}
#[test]
#[ignore]
fn arithmetics {
assert_eq!(2 + 2, 5);
}
Source: toggle_macro_delimiter.rs
Change macro delimiters in the order of ( → { → [ → (
.
macro_rules! sth {
() => {};
}
sth!┃( );
macro_rules! sth {
() => {};
}
sth!{ }
Source: unmerge_match_arm.rs
Splits the current match with a |
pattern into two arms with identical bodies.
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move(..) ┃| Action::Stop => foo(),
}
}
enum Action { Move { distance: u32 }, Stop }
fn handle(action: Action) {
match action {
Action::Move(..) => foo(),
Action::Stop => foo(),
}
}
Source: unmerge_use.rs
Extracts single use item from use list.
use std::fmt::{Debug, Display┃};
use std::fmt::{Debug};
use std::fmt::Display;
Source: unnecessary_async.rs
Removes the async
mark from functions which have no .await
in their body.
Looks for calls to the functions and removes the .await
on the call site.
pub asy┃nc fn foo() {}
pub async fn bar() { foo().await }
pub fn foo() {}
pub async fn bar() { foo() }
Source: unqualify_method_call.rs
Transforms universal function call syntax into a method call.
fn main() {
std::ops::Add::add┃(1, 2);
}
use std::ops::Add;
fn main() {
1.add(2);
}
Source: unwrap_block.rs
This assist removes if…else, for, while and loop control statements to just keep the body.
fn foo() {
if true {┃
println!("foo");
}
}
fn foo() {
println!("foo");
}
Source: unwrap_return_type.rs
Unwrap the function’s return type.
fn foo() -> Option<i32>┃ { Some(42i32) }
fn foo() -> i32 { 42i32 }
Source: unwrap_return_type.rs
Unwrap the function’s return type.
fn foo() -> Result<i32>┃ { Ok(42i32) }
fn foo() -> i32 { 42i32 }
Source: unwrap_tuple.rs
Unwrap the tuple to different variables.
fn main() {
┃let (foo, bar) = ("Foo", "Bar");
}
fn main() {
let foo = "Foo";
let bar = "Bar";
}
Source: wrap_return_type.rs
Wrap the function’s return type into Option.
fn foo() -> i32┃ { 42i32 }
fn foo() -> Option<i32> { Some(42i32) }
Source: wrap_return_type.rs
Wrap the function’s return type into Result.
fn foo() -> i32┃ { 42i32 }
fn foo() -> Result<i32, ${0:_}> { Ok(42i32) }
Source: wrap_unwrap_cfg_attr.rs
Wraps an attribute to a cfg_attr attribute or unwraps a cfg_attr attribute to the inner attributes.
#[derive┃(Debug)]
struct S {
field: i32
}
#[cfg_attr(┃, derive(Debug))]
struct S {
field: i32
}