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 Gives Up On Crypto Blockchain Project

Durov said on his Telegram channel today that the two and a half year blockchain and crypto project has been put to sleep. Ironically, after leaving Russia because the government wanted his encryption keys to his social media firm, Durov’s cryptocurrency idea lost steam because of a U.S. court. “The technology we created allowed for an open, free, decentralized exchange of value and ideas. TON had the potential to revolutionize how people store and transfer funds and information,” he wrote on his channel. “Unfortunately, a U.S. court stopped TON from happening.”

Telegram Be The Next Best SPAC

I have no inside knowledge of a potential stock listing of the popular anti-Whatsapp messaging app, Telegram. But I know this much, judging by most people I talk to, especially crypto investors, if Telegram ever went public, people would gobble it up. I know I would. I’m waiting for it. So is Sergei Sergienko, who claims he owns $800,000 of Telegram’s pre-initial coin offering (ICO) tokens. “If Telegram does a SPAC IPO, there would be demand for this issue. It would probably outstrip the interest we saw during the ICO. Why? Because as of right now Telegram looks like a liberal application that can accept anyone - right after WhatsApp and others have turn on the censorship,” he says.

Rust from ar


Telegram Rust
FROM USA