4 ms·
>strings aren’t actually simple arrays of characters in Rust like they are in C, but there is an underlying array on the heap Not a Rust expert, but to my unde
by scoutt 6y ago
>strings aren’t actually simple arrays of characters in Rust like they are in C, but there is an underlying array on the heap
Not a Rust expert, but to my understanding, 'string' is an array of characters, not necessarily living in the heap.
The object 'String' (with capital S) might be, but with &str I can have a constant array of characters that is not in the heap and not even in the stack: it's in the code (.text code segment[1]?, or EEPROM or flash, for embedded folks).
If I understood it correctly, &str is a slice with a pointer to that piece of code. Of course being const, it cannot be changed. I can copy it into a String and manipulate it (append, insert, etc.), and that's where the heap is used.
&str, as an hypothetical struct, it may be in the stack, initialized in-scope with (probably) a pointer to somewhere in .text plus some bytes for length or other information.
[1] https://en.wikipedia.org/wiki/Code_segment https://en.wikipedia.org/wiki/Code_segment
- deleted 6y ago[deleted]
- brundolf 6y ago&str is not necessarily a static string literal; it's a slice of any string, living anywhere (including on the heap inside a String). Technically speaking, it can't be mutated because it's a non-mutable reference (like any other non-mutable reference). &mut str is a thing that can exist, and is mutable, it's just that you can't get one of those for a static (literal) string that lives in the code.
- scoutt 6y agoThanks. Yes, of course it can point to something in the heap. My comment was related to GP's "but there is an underlying array on the heap" and I wanted to say that &str is not always necessarily in the heap. I missed that part.