C
C
CNNRNN2020-02-05 10:03:01
Rust
CNNRNN, 2020-02-05 10:03:01

Is memory allocated when creating &str?

I have an array of bytes and I want to convert the first 10 bytes to a string.
if i do String::from_utf8_lossy() it will return &str.
Do I understand correctly that &str is the address of those 10 bytes and in fact the memory will be allocated only when the link is created? Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Demin, 2020-02-13
@keksmen

There is some misunderstanding here. Memory allocation usually means its allocation in dynamic memory , while variables and arguments live in stack memory .
And now, answering your question:

  • Yes, &str is really just an address of bytes and the length of the slice that the address refers to.
  • No, dynamic memory is not allocated in this case, because storage on the stack is predictable, unambiguous, and sufficient for this case.

S
Somewhere Intech, 2020-02-05
@john36allTa

Forgot about the length ..

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question