Why is & str called a slice in Rust?

This makes me think that this is a substring of some other line, when it is only a line allocated by the stack. Do I have a misunderstanding of this?

+4
source share
1 answer

when it is just a line allocated by the stack

This is not entirely correct. String slice ( &str) is conceptually built from two things:

  • Pointer to the beginning of a line.
  • The number of bytes per line.

A pointer can refer to data on the stack, to a heap, or even to persistent program data.

It is called a string slice because it reflects a regular slice ( &[T]), which is the same two parts: pointer and length.

u8 (&[u8]), : UTF-8.

, " " " " -, . :

let test_scores = [0, 10, 100];
let all_scores = &test_scores[..]; // or &test_scores[0..3]
let some_scores = &test_scores[0..1];
+14

Source: https://habr.com/ru/post/1626033/


All Articles