0Pricing
Learn Rust Coding · Урок

Связывание с помощью @

Захват и проверка

«Связывание с помощью @» — бесплатный урок Learn Rust Coding на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Learn Rust Coding, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Learn Rust Coding содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

The @ Binding Operator

The @ operator lets you test a value against a pattern and bind it to a name at the same time. You get both the check and the value.

The Problem It Solves

With a range pattern you know a value fell in range, but you lose access to the specific value. @ captures it while still testing the range.

Basic @ Binding

Here we match a number in a range and keep its exact value via id.

fn main() {
    let n = 5;
    match n {
        id @ 1..=5 => println!("got {id} in range"),
        _ => println!("out of range"),
    }
}

Without @

Compare: a plain range arm matches but cannot name the value, so you cannot print which number matched.

fn main() {
    let n = 5;
    match n {
        1..=5 => println!("in range (value unknown here)"),
        _ => println!("out of range"),
    }
}

@ With Enum Data

Bind a field while also constraining it. Here we capture the id only if it falls in a valid range.

enum Message {
    Hello { id: i32 },
}

fn main() {
    let msg = Message::Hello { id: 7 };
    match msg {
        Message::Hello { id: id @ 3..=10 } => {
            println!("valid id {id}");
        }
        Message::Hello { id } => {
            println!("other id {id}");
        }
    }
}

Binding the Whole Value

@ can also bind an entire structured value while a nested pattern checks its parts.

fn main() {
    let point = (3, 4);
    match point {
        p @ (x, _) if x > 0 => println!("{:?} has positive x", p),
        p => println!("{:?}", p),
    }
}

Combining with |

You can bind across alternative patterns. The name must appear in each alternative branch.

fn main() {
    let code = 404;
    match code {
        c @ (400 | 404 | 500) => println!("error code {c}"),
        c => println!("code {c}"),
    }
}

@ in if let

Bindings with @ work in if let too.

fn main() {
    let value = Some(50);
    if let Some(n @ 1..=100) = value {
        println!("in range: {n}");
    }
}

When to Reach for @

Use @ when you need both:

  • To restrict a value with a range or sub-pattern
  • To use that exact value in the arm body

Without both needs, a plain binding or pattern is simpler.

Readability

The form reads as name @ pattern: bind name if it matches pattern. Keep names descriptive so the intent is clear.

Bucketing with @

A common use is sorting a value into labeled buckets while keeping the original number for reporting.

fn classify(temp: i32) -> String {
    match temp {
        t @ ..=0 => format!("freezing ({t})"),
        t @ 1..=20 => format!("cool ({t})"),
        t @ 21..=30 => format!("warm ({t})"),
        t => format!("hot ({t})"),
    }
}

fn main() {
    println!("{}", classify(25));
}

Quick Check

What does the @ operator do in a pattern like id @ 1..=5?

Recap

You learned the @ binding operator:

  • It binds a value to a name while testing it against a pattern
  • Solves the lost-value problem with range patterns
  • Works with enum data, tuples, | alternatives, and if let
  • Use it when you need both the constraint and the value

Часто задаваемые вопросы

Урок «Связывание с помощью @» бесплатный?

Да — полный текст урока «Связывание с помощью @» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Learn Rust Coding, подпишись на CoddyKit PRO. Курс Learn Rust Coding содержит 4 уроков всего.

Чему я научусь в уроке «Связывание с помощью @»?

Захват и проверка Ты практикуешь Learn Rust Coding с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Learn Rust Coding?

Предыдущий опыт не требуется. Learn Rust Coding на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.

Сколько времени занимает урок «Связывание с помощью @»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Learn Rust Coding?

Да. Каждый урок Learn Rust Coding включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Подробно о match
  2. if let и while let
  3. Связывание с помощью @
  4. Деструктуризация
← Назад к Learn Rust Coding