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 today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

How to Invest in Bitcoin?

Like a stock, you can buy and hold Bitcoin as an investment. You can even now do so in special retirement accounts called Bitcoin IRAs. No matter where you choose to hold your Bitcoin, people’s philosophies on how to invest it vary: Some buy and hold long term, some buy and aim to sell after a price rally, and others bet on its price decreasing. Bitcoin’s price over time has experienced big price swings, going as low as $5,165 and as high as $28,990 in 2020 alone. “I think in some places, people might be using Bitcoin to pay for things, but the truth is that it’s an asset that looks like it’s going to be increasing in value relatively quickly for some time,” Marquez says. “So why would you sell something that’s going to be worth so much more next year than it is today? The majority of people that hold it are long-term investors.”

Rust from ms


Telegram Rust
FROM USA