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.

What Is Bitcoin?

Bitcoin is a decentralized digital currency that you can buy, sell and exchange directly, without an intermediary like a bank. Bitcoin’s creator, Satoshi Nakamoto, originally described the need for “an electronic payment system based on cryptographic proof instead of trust.” Each and every Bitcoin transaction that’s ever been made exists on a public ledger accessible to everyone, making transactions hard to reverse and difficult to fake. That’s by design: Core to their decentralized nature, Bitcoins aren’t backed by the government or any issuing institution, and there’s nothing to guarantee their value besides the proof baked in the heart of the system. “The reason why it’s worth money is simply because we, as people, decided it has value—same as gold,” says Anton Mozgovoy, co-founder & CEO of digital financial service company Holyheld.

Rust from sg


Telegram Rust
FROM USA