Write and call a function in Rust

InstructorPascal Precht

Share this video with your friends

Send Tweet

In this lesson we'll create a new function that receives parameters and called inside our program's main() function.

Michele Nasti
~ 5 years ago

Why do we have to use the .to_string() method call? What is the type of "Pascal" ? I see from the compiler that it's &str, how does it work under the hood?

Pascal Prechtinstructor
~ 5 years ago

Hey Michele!

This is an excellent question. So as you've already pointed out "Pascal" is of type &str which is a "string slice". A string slice is preallocated readonly memory that ships with the program.

A String, which is the type you get when you call .to_string() on a &str, is a pointer type that allocates the text on the heap.

This may or may not make too much sense right now, because a good basic understanding of how Rust manages memory is needed for that. I will cover this in future videos, but for now I've put together an article that explains exactly that:

https://twitter.com/PascalPrecht/status/1234833467239731205

J. Matthew
~ 5 years ago

This is an excellent question. So as you've already pointed out "Pascal" is of type &str which is a "string slice". A string slice is preallocated readonly memory that ships with the program.

A String, which is the type you get when you call .to_string() on a &str, is a pointer type that allocates the text on the heap.

Huh, that's really interesting. I was wondering about @Michele's question, too. I would have guessed that &str was itself a pointer based on the ampersand, but it sounds like it's slightly different. I'm not super-strong on pointers, though. I'll check out that article; thanks for putting it together!

Pascal Prechtinstructor
~ 5 years ago

I would have guessed that &str was itself a pointer based on the ampersand, but it sounds like it's slightly different.

This is very correct. I probably expressed myself not correctly. So here's the deal:

  • A String is a pointer type that, in memory, stores the pointer, length of the text and capacity on the stack, while the actual text is being stored on the heap in a buffer.
  • A str is a slice, or substring of either such data in a buffer or preallocated memory. But because the data lives either on the heap or the preallocated memory of the program, you always need a reference to access the data
  • A &str is a pointer to a str. As mentioned above, a &str is a reference that points to a str which either lives in a buffer (and represents an entire or substring of a String), or in preallocated memory.

I know this is tough to grasp (trust me, took me a while too), so I've written this article that aims to help:

https://blog.thoughtram.io/string-vs-str-in-rust/

J. Matthew
~ 5 years ago

I know this is tough to grasp (trust me, took me a while too), so I've written this article that aims to help

Thanks, I read that article and Rust's documentation on Ownership/slices, and I get it now.