lotsoftools

Understanding Rust Error E0121

Introduction

Rust Error E0121 occurs when a type placeholder (_) is used within a type on an item's signature. This article will explain the error and demonstrate how to resolve it through code examples.

Type Placeholder Usage and Error Cases

The type placeholder, represented by the underscore (_), is a convenient feature in Rust when the type is either unimportant or can be inferred by the compiler. However, it should not be used in an item's signature, including function return types and static variables. Let's examine the following erroneous code example:

fn main() {
fn foo() -> _ { 5 } // error

static BAR: _ = "test"; // error
}

In the example above, we have used underscores as placeholders for the return type of the function foo() and the type of the static variable BAR, which results in Rust Error E0121.

How to Fix Rust Error E0121

To resolve Rust Error E0121, you need to provide the explicit type for the item signatures. In the example, replace the underscore (_) with the appropriate types. See the corrected code below:

fn main() {
fn foo() -> i32 { 5 } // ok!

static BAR: &str = "test"; // ok!
}

The function foo() now has its return type explicitly set to i32, and the static variable BAR is explicitly set to be a reference to a string (&str).

Using Type Placeholder Outside Item Signatures

You can still use the type placeholder (_) outside item signatures when the compiler can infer the type. Here's an example:

fn main() {
let x = "a4a".split('4')
    .collect::<Vec<_>>(); // No need to precise the Vec's generic type.
}

In this case, the type placeholder is used inside the angle brackets while constructing a Vec. Since the compiler can infer the type of elements within the Vec, the underscore can be used without triggering Rust Error E0121.