What is the difference between &str and str?

it’s incorrect:

fn main() {

    let hello = String::from("Hello World!!");

    let s = &hello[0..4];
    
    let temp_s = s[..1];

}

but this is correct:

fn main() {

    let hello = String::from("Hello World!!");

    let s = &hello[0..4];

    let temp_s = &s[..1];

}

hello is a String.

s is an &str, and is a reference to a str.

Why s[. .1] is incorrect.

What is the type of &s[..1]

I'm confused and any help is appreciated.

Since s is a reference, s[..1] would extract a 1-element subslice in an array of references, not the first element of whatever s refers to. So the first problem is that you are working with the reference, a usize value in this case, rather than indirecting through the reference to the string. The second problem is that s is not declared as a type that supports slice extraction, such as an array or vec, so slice extraction is invalid. The third problem is that type inference would make temp_s be a reference (or actually a length-1 array of references) rather than a string character, since temp_s will be the same type as s[..1].

However, there's an even earlier problem in your code: you extract the first four bytes from hello, which is a UTF-8 string. Suppose that string were "你好", which means "hello" in Chinese. One or both of those characters might encode in three bytes, which means that your extraction of the first four bytes could truncate in the middle of the second character. That's why indexing by integers is not defined on Rust strings.

2 Likes

Because, according to Index docs and SliceIndex docs they refer to, if s has type &str, s[range] has type str, and str is an unsized type - just a bunch of bytes, in fact, with the additional requirement of being valid UTF-8.

s[..1] has type str, so &s[..1] has type &str. More correctly, it has type &'a str for some unnamed lifetime 'a, derived from the reference's usage.

3 Likes

明白了。
Your answer was very precise, thank you very much.

不客气 (tr: you're welcome)

1 Like

你会说中文吗?我是一个Rust新手,还有很多问题想请教你(大多数是菜鸟问题),不过我的英文不太好

1983年,我访问了中国,因此,1984年,我首先与北京的母语人士一起学习汉语。 2009年,我再次学习了中文。 我会尽全力为您提供帮助,有时会使用Google翻译。 您也可以向他人寻求帮助; 这个论坛上有很多人会读和写中文。

1 Like

原来如此,再次感谢你!

If you have a serious question abouy a different topic, first search this forum for existing threads on that topic. If no thread is appropriate or your question isn't answered, create a new thread focused on that topic. Don't hijack threads devoted to other topics.

tr: 如果您对其他主题有疑问,请首先在此论坛中搜索有关该主题的现有主题。 如果没有合适的主题或您的问题没有得到回答,请创建一个针对该主题的新主题。 不要劫持专门讨论其他主题的主题。

2 Likes