Telegram Group & Telegram Channel
👣 Вопрос:
Какие строки и в каком порядке будут выведены на консоль при запуске этой программы? Приведите полный список выводимых сообщений.этого кода.


use std::mem;

struct Tracer(&'static str);

impl Drop for Tracer {
fn drop(&mut self) {
println!("Dropping {}", self.0);
}
}

struct Container {
tracer: Tracer,
}

fn make_tracer(name: &'static str) -> Tracer {
println!("Creating {}", name);
Tracer(name)
}

fn main() {
let a = make_tracer("a");
let b = make_tracer("b");
{
let temp = make_tracer("temp");
println!("Inside block");
// temp перемещается в c
let c = temp;
println!("Exiting block");
} // <- здесь c (то есть «temp») умирает

let mut container = Container {
tracer: make_tracer("container1"),
};
// замена поля: старый контейнер1 будет сброшен
container.tracer = make_tracer("container2");

println!("Before dropping b explicitly");
mem::drop(b);
println!("End of main");
} // <- здесь умирают: container.tracer ("container2"), затем a


🔜 Ответ
Вот что выведется на консоль, построчно:
```bash
Creating a
Creating b
Creating temp
Inside block
Exiting block
Dropping temp
Creating container1
Creating container2
Dropping container1
Before dropping b explicitly
Dropping b
End of main
Dropping container2
Dropping a```

Пояснение по шагам:

let a = make_tracer("a");
Сначала вызывается make_tracer("a"), который печатает
Creating a
и возвращает Tracer("a").

let b = make_tracer("b");
Аналогично:
Creating b

Блок { … }:

let temp = make_tracer("temp"); → Creating temp

println!("Inside block"); → Inside block

let c = temp; — просто перемещение, без нового вывода.

println!("Exiting block"); → Exiting block

В конце блока выходит из области видимости c (он же temp), срабатывает Drop → Dropping temp

Инициализация container:

rust
let mut container = Container {
tracer: make_tracer("container1"),
};
→ Creating container1

Перезапись поля tracer:

```rust
container.tracer = make_tracer("container2");
Сначала вычисляется правая часть → Creating container2.
Затем старый container.tracer (то есть container1) сбрасывается → Dropping container1.```

Явное удаление b:

```rust
println!("Before dropping b explicitly");
mem::drop(b);
→ Before dropping b explicitly
Затем drop(b) вызывает Drop для b → Dropping b```

Выход из main:

```rust
println!("End of main");
→ End of main```

После этого по правилам Rust объекты уничтожаются в порядке обратном созданию (LIFO):

Сначала поле container.tracer (уже “container2”) → Dropping container2

Затем переменная a → Dropping a

Таким образом и получается приведённая последовательность.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/rust_code/918
Create:
Last Update:

👣 Вопрос:
Какие строки и в каком порядке будут выведены на консоль при запуске этой программы? Приведите полный список выводимых сообщений.этого кода.


use std::mem;

struct Tracer(&'static str);

impl Drop for Tracer {
fn drop(&mut self) {
println!("Dropping {}", self.0);
}
}

struct Container {
tracer: Tracer,
}

fn make_tracer(name: &'static str) -> Tracer {
println!("Creating {}", name);
Tracer(name)
}

fn main() {
let a = make_tracer("a");
let b = make_tracer("b");
{
let temp = make_tracer("temp");
println!("Inside block");
// temp перемещается в c
let c = temp;
println!("Exiting block");
} // <- здесь c (то есть «temp») умирает

let mut container = Container {
tracer: make_tracer("container1"),
};
// замена поля: старый контейнер1 будет сброшен
container.tracer = make_tracer("container2");

println!("Before dropping b explicitly");
mem::drop(b);
println!("End of main");
} // <- здесь умирают: container.tracer ("container2"), затем a


🔜 Ответ
Вот что выведется на консоль, построчно:
```bash
Creating a
Creating b
Creating temp
Inside block
Exiting block
Dropping temp
Creating container1
Creating container2
Dropping container1
Before dropping b explicitly
Dropping b
End of main
Dropping container2
Dropping a```

Пояснение по шагам:

let a = make_tracer("a");
Сначала вызывается make_tracer("a"), который печатает
Creating a
и возвращает Tracer("a").

let b = make_tracer("b");
Аналогично:
Creating b

Блок { … }:

let temp = make_tracer("temp"); → Creating temp

println!("Inside block"); → Inside block

let c = temp; — просто перемещение, без нового вывода.

println!("Exiting block"); → Exiting block

В конце блока выходит из области видимости c (он же temp), срабатывает Drop → Dropping temp

Инициализация container:

rust
let mut container = Container {
tracer: make_tracer("container1"),
};
→ Creating container1

Перезапись поля tracer:

```rust
container.tracer = make_tracer("container2");
Сначала вычисляется правая часть → Creating container2.
Затем старый container.tracer (то есть container1) сбрасывается → Dropping container1.```

Явное удаление b:

```rust
println!("Before dropping b explicitly");
mem::drop(b);
→ Before dropping b explicitly
Затем drop(b) вызывает Drop для b → Dropping b```

Выход из main:

```rust
println!("End of main");
→ End of main```

После этого по правилам Rust объекты уничтожаются в порядке обратном созданию (LIFO):

Сначала поле container.tracer (уже “container2”) → Dropping container2

Затем переменная a → Dropping a

Таким образом и получается приведённая последовательность.

BY Rust


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/rust_code/918

View MORE
Open in Telegram


Rust Telegram | DID YOU KNOW?

Date: |

Telegram Auto-Delete Messages in Any Chat

Some messages aren’t supposed to last forever. There are some Telegram groups and conversations where it’s best if messages are automatically deleted in a day or a week. Here’s how to auto-delete messages in any Telegram chat. You can enable the auto-delete feature on a per-chat basis. It works for both one-on-one conversations and group chats. Previously, you needed to use the Secret Chat feature to automatically delete messages after a set time. At the time of writing, you can choose to automatically delete messages after a day or a week. Telegram starts the timer once they are sent, not after they are read. This won’t affect the messages that were sent before enabling the feature.

The lead from Wall Street offers little clarity as the major averages opened lower on Friday and then bounced back and forth across the unchanged line, finally finishing mixed and little changed.The Dow added 33.18 points or 0.10 percent to finish at 34,798.00, while the NASDAQ eased 4.54 points or 0.03 percent to close at 15,047.70 and the S&P 500 rose 6.50 points or 0.15 percent to end at 4,455.48. For the week, the Dow rose 0.6 percent, the NASDAQ added 0.1 percent and the S&P gained 0.5 percent.The lackluster performance on Wall Street came on uncertainty about the outlook for the markets following recent volatility.

Rust from jp


Telegram Rust
FROM USA