Your code example is not very complete. The part that actually causes the error can't be seen in your example.

I guess that your code looks something like this:

pub fn function1(s: String) -> i32 {
    let index: &i32 = &1;
    let substring = (&s[index..]).to_string();
    let counter = function1(substring);
    10
}
error[E0277]: the type `String` cannot be indexed by `RangeFrom<&i32>`
 --> src/main.rs:3:23
  |
3 |     let substring = (&s[index..]).to_string();
  |                       ^^^^^^^^^^ `String` cannot be indexed by `RangeFrom<&i32>`
  |
  = help: the trait `Index<RangeFrom<&i32>>` is not implemented for `String`

Problems

  • index must be a usize, but it is an &i32. This is the main error that you see.
  • You cannot slice a string directly, you need to convert from char-based indices to byte-based indices first. This can be done by iterating through char_indices().

Here is a rough sketch of how this might look like:

pub fn function1(s: String) -> i32 {
    println!("s: {}", s);

    let index: &i32 = &1;

    // Try to convert the index to a byte position
    let substring = match s.char_indices().nth(*index as usize) {
        // If a position with the given index was found in the string, create a substring
        Some((pos, _)) => (&s[pos..]).to_string(),
        // Else, create an empty string
        None => "".to_string(),
    };

    // Break if the substring is empty, otherwise we would have an infinite recursion
    if substring.is_empty() {
        return 0;
    }

    let counter = function1(substring);
    counter + 1
}

fn main() {
    let input_str = "".to_string();
    let result = function1(input_str);
    println!("Result: {}", result);
}
s: 
s: 
s: 
s: 
Result: 3

Slicing vs copying

With every iteration of your function, you are creating a new copy of the string. This is quite slow, and I don't see a reason why this would be necessary in your case.

What you really want is a slice of the input string. This doesn't copy any data, it simply references a part of the original string.

To achieve that, you would have to change your parameter type from String to &str. There is no reason your function would need to take ownership. Even if you want to take ownership, then to_string() would do so, as it creates a copy of the data. So there really is no reason to use String as the parameter type.

pub fn function1(s: &str) -> i32 {
    println!("s: {}", s);

    let index: &i32 = &1;

    // Try to convert the index to a byte position
    let substring = match s.char_indices().nth(*index as usize) {
        // If a position with the given index was found in the string, create a substring slice
        Some((pos, _)) => &s[pos..],
        // Else, use an empty string
        None => "",
    };

    // Break if the substring is empty, otherwise we would have an infinite recursion
    if substring.is_empty() {
        return 0;
    }

    let counter = function1(substring);
    counter + 1
}

fn main() {
    let input_str = "".to_string();
    let result = function1(&input_str);
    println!("Result: {}", result);
}
s: 
s: 
s: 
s: 
Result: 3
Answer from Finomnis on Stack Overflow
🌐
The Rust Programming Language
doc.rust-lang.org › book › ch04-03-slices.html
The Slice Type - The Rust Programming Language
Figure 4-7: A string slice referring to part of a String · With Rust’s .. range syntax, if you want to start at index 0, you can drop the value before the two periods.
🌐
Rust
doc.rust-lang.org › std › primitive.str.html
str - Rust
November 3, 2020 - A string slice (&str) is made of bytes (u8), and a byte slice (&[u8]) is made of bytes, so this function converts between the two. Not all byte slices are valid string slices, however: &str requires that it is valid UTF-8.
Discussions

How to get a substring of a String
Hi, what is the best way to get a substring of a String? I couldn't find a substr method or similar. Let's assume I have a String like "Golden Eagle" and I want to get the first 6 characters, that is "Golden". How can I do that? Markus More on users.rust-lang.org
🌐 users.rust-lang.org
6
May 14, 2015
Newbie Question: String Slices
Everything can be represented as a &str so with a reference to a slice as a parameter the function can be used with both strings, string literals and slices. A &str is just a fat pointer to you string so it costs nothing to have around. I like this blog post about slicing vs string vs referencing: https://blog.thoughtram.io/string-vs-str-in-rust/ . It explains the subject perfectly. It may help you a bit with this. It helped me. More on reddit.com
🌐 r/rust
10
5
December 13, 2020
&str is same with slice?
How could it be a slice when I made it myself. If it's a slice means that rust stores strings then I borrow those values for my own code? I can understand if the slice is from String like below code. But when &str is called slice I don't know, why we have to borrow value. fn main() { let s = S... More on users.rust-lang.org
🌐 users.rust-lang.org
1
2
August 22, 2023
Basic-Topic-String-and-string-Slice
There are 2 types of strings in Rust namely , String (mutable) and string slice "str". Why I need to annotate the type as reference when I use string slice . For example I need to use like let str1 : &str = "Chennai" ; Why not like let str1: str = "Chennai" When I use without reference, the ... More on users.rust-lang.org
🌐 users.rust-lang.org
0
April 24, 2020
Top answer
1 of 2
2

Your code example is not very complete. The part that actually causes the error can't be seen in your example.

I guess that your code looks something like this:

pub fn function1(s: String) -> i32 {
    let index: &i32 = &1;
    let substring = (&s[index..]).to_string();
    let counter = function1(substring);
    10
}
error[E0277]: the type `String` cannot be indexed by `RangeFrom<&i32>`
 --> src/main.rs:3:23
  |
3 |     let substring = (&s[index..]).to_string();
  |                       ^^^^^^^^^^ `String` cannot be indexed by `RangeFrom<&i32>`
  |
  = help: the trait `Index<RangeFrom<&i32>>` is not implemented for `String`

Problems

  • index must be a usize, but it is an &i32. This is the main error that you see.
  • You cannot slice a string directly, you need to convert from char-based indices to byte-based indices first. This can be done by iterating through char_indices().

Here is a rough sketch of how this might look like:

pub fn function1(s: String) -> i32 {
    println!("s: {}", s);

    let index: &i32 = &1;

    // Try to convert the index to a byte position
    let substring = match s.char_indices().nth(*index as usize) {
        // If a position with the given index was found in the string, create a substring
        Some((pos, _)) => (&s[pos..]).to_string(),
        // Else, create an empty string
        None => "".to_string(),
    };

    // Break if the substring is empty, otherwise we would have an infinite recursion
    if substring.is_empty() {
        return 0;
    }

    let counter = function1(substring);
    counter + 1
}

fn main() {
    let input_str = "".to_string();
    let result = function1(input_str);
    println!("Result: {}", result);
}
s: 
s: 
s: 
s: 
Result: 3

Slicing vs copying

With every iteration of your function, you are creating a new copy of the string. This is quite slow, and I don't see a reason why this would be necessary in your case.

What you really want is a slice of the input string. This doesn't copy any data, it simply references a part of the original string.

To achieve that, you would have to change your parameter type from String to &str. There is no reason your function would need to take ownership. Even if you want to take ownership, then to_string() would do so, as it creates a copy of the data. So there really is no reason to use String as the parameter type.

pub fn function1(s: &str) -> i32 {
    println!("s: {}", s);

    let index: &i32 = &1;

    // Try to convert the index to a byte position
    let substring = match s.char_indices().nth(*index as usize) {
        // If a position with the given index was found in the string, create a substring slice
        Some((pos, _)) => &s[pos..],
        // Else, use an empty string
        None => "",
    };

    // Break if the substring is empty, otherwise we would have an infinite recursion
    if substring.is_empty() {
        return 0;
    }

    let counter = function1(substring);
    counter + 1
}

fn main() {
    let input_str = "".to_string();
    let result = function1(&input_str);
    println!("Result: {}", result);
}
s: 
s: 
s: 
s: 
Result: 3
2 of 2
1

You couldn't indexing a string in rust, because strings are encoded in UTF-8. You could use the method chars and/or char_indices

As from your given code, I can't figure out what method you should use. Have a look at the rust doc.

For further information:

https://doc.rust-lang.org/std/string/struct.String.html

https://doc.rust-lang.org/std/string/struct.String.html#method.chars

https://doc.rust-lang.org/std/string/struct.String.html#method.char_indices

https://doc.rust-lang.org/std/string/struct.String.html#method.split_whitespace

🌐
Rust Programming Language
users.rust-lang.org › help
How to get a substring of a String - help - The Rust Programming Language Forum
May 14, 2015 - Hi, what is the best way to get a substring of a String? I couldn't find a substr method or similar. Let's assume I have a String like "Golden Eagle" and I want to get the first 6 characters, that is "Golden". How ca…
Find elsewhere
🌐
Rust
docs.rs › slicestring
slicestring - Rust
slicestring is a crate for slicing Strings. It provides the `slice()` method for `String` and `&str`. It takes the index-range as an argument, whereby also a negative value can be passed for the second index. It slices the `String` or `&str` and returns a the sliced one as a `String`.
🌐
Rust Programming Language
users.rust-lang.org › t › basic-topic-string-and-string-slice › 41479
Basic-Topic-String-and-string-Slice - The Rust Programming Language Forum
April 24, 2020 - There are 2 types of strings in Rust namely , String (mutable) and string slice "str". Why I need to annotate the type as reference when I use string slice . For example I need to use like let str1 : &str = "Chennai" ; Why not like let str1: str = "Chennai" When I use without reference, the rust compiler says that error[E0308]: mismatched types --> string1.rs:4:22 | 4 | let str1: str = "Chennai"; | --- ^^^^^^^^^ expected `str`, found `&str` | ...
🌐
DEV Community
dev.to › alexmercedcoder › in-depth-guide-to-working-with-strings-in-rust-1522
In-Depth Guide to Working with Strings in Rust - DEV Community
September 14, 2024 - Rust's memory management model introduces some unique aspects to string handling, making it different from other languages. &str, also called a string slice, is an immutable reference to a sequence of UTF-8 characters.
🌐
MIT
web.mit.edu › rust-lang_v1.25 › arch › amd64_ubuntu1404 › share › doc › rust › html › book › second-edition › ch04-03-slices.html
Slices - The Rust Programming Language
This slice has the type &[i32]. It works the same way as string slices do, by storing a reference to the first element and a length. You’ll use this kind of slice for all sorts of other collections. We’ll discuss these collections in detail when we talk about vectors in Chapter 8. The concepts of ownership, borrowing, and slices are what ensure memory safety in Rust programs at compile time.
🌐
Hacker News
news.ycombinator.com › item
One thing I don't like about Rust is how taking a slice of a string can cause a ... | Hacker News
January 11, 2019 - I would prefer it if this feature didn't exist at all rather than cause runtime panics · https://play.rust-lang.org/?gist=e02ce5e9aacfee3a2b4917d5624
🌐
DEV Community
dev.to › dsysd_dev › string-vs-str-in-rust-understanding-the-fundamental-differences-for-efficient-programming-4og8
String vs str in Rust: Understanding the Fundamental Differences for Efficient Programming - DEV Community
July 31, 2023 - In summary, "String" is a dynamic and mutable string type that owns its data, while "str" (String Slice) is an immutable reference to a fixed portion of a string and does not own the data.
🌐
Medium
medium.com › @python-javascript-php-html-css › understanding-string-slices-in-rust-why-str-needs-an-ampersand-7b99deff3b71
Understanding String Slices in Rust: Why &str Needs an Ampersand
November 18, 2024 - In the provided example, slicing the string “hello” into smaller parts using index ranges highlighted an important distinction between `str` and `&str`. A string slice, such as `&str`, is essentially a borrowed reference to a part of the string.
Top answer
1 of 3
6

You can't return a reference to a locally allocated String because the string is dropped when the function returns. There's no way to finagle your way around that. A &str is simply a bad match for the type of data you want to return.

The most straightforward fix is to return an owned String.

Copyfn my_func(input: &str) -> String {
    match input {
        "a" => "Alpha".to_string(),
        _ => format!("'{}'", "Quoted" ), 
    }
}

Another is to return a Cow<'_, str>, which can hold either a borrowed or owned string depending on which you have. It's a bit fussy, but it does avoids unnecessary allocations. I only recommend this if efficiency is of utmost important; otherwise, just return String.

Copyfn my_func(input: &str) -> Cow<'_, str> {
    match input {
        "a" => "Alpha".into(),
        _ => format!("'{}'", "Quoted" ).into(), 
    }
}

I'll also mention a third option -- for educational purposes, not for actual use, since it leaks memory. You can get a 'static reference to an owned object if you leak it. Leaked memory is valid for the remainder of the program since it's never freed, and thus you can in fact get a reference to it.

Copy// Warning: Do not use! Leaks memory.
fn my_func(input: &str) -> &'static str {
    match input {
        "a" => "Alpha",
        _ => Box::leak(format!("'{}'", "Quoted").into_boxed_str()), 
    }
}
2 of 3
1

The problem is that the arm with format!().as_str() produces an owned String, as soon as your function returns, the String is dropped and the &str reference would become invalid.

You can use std::borrow::Cow to allow a function to return both owned or borrowed strings.

🌐
Reddit
reddit.com › r/rust › take a string slice and returns a reference to its first character
r/rust on Reddit: Take a string slice and returns a reference to its first character
May 10, 2024 -

Hey all,

I am learning Rust, and was not sure how to approach the following:

Write a function `first_char` that takes a string slice and returns a reference to its first character.`

My attempt:

fn first_char(s: &str) -> Option<&char> {
    s.chars().next().as_ref()
}

However, Rust complains that it "cannot return value referencing temporary value
returns a value referencing data owned by the current function"

Is there any way to solve the above? Any pointers would be appreciated

🌐
DEV Community
dev.to › francescoxx › slices-in-rust-g6
Slices in Rust - DEV Community
March 5, 2024 - As a final note, the type of s2 is &str, which is a slice of a string. This means that s2 is a reference to a contiguous sequence of characters in memory. So we can remove the &s2 from the first_word function and the code will still work. In this lesson, we explored the Slice type in Rust.
🌐
YouTube
youtube.com › watch
Rust String vs str slices - YouTube
One of the more complex topics in Rust, this is an in depth look at Strings and str slices.This Rust programming language tutorial series is aimed at easing ...
Published   October 20, 2019
🌐
Rust Programming Language
users.rust-lang.org › help
Why String can be sliced with usize index? - help - The Rust Programming Language Forum
February 6, 2022 - Rust disallows random access to strings, but allows slicing strings using usize ranges, which I think is an inconsistent design. let string = String::from("🌊🌊🌊"); println!("{}", string[1]); // Compile time error: // `String` cannot ...
🌐
Eze Sunday
ezesunday.com › home › rust string manipulations
Rust string manipulations - Eze Sunday
August 23, 2025 - The + operator (provided by the Add trait) isn’t implemented for string slices, so you can’t directly concatenate them. However, you can achieve the same result with this approach: let new_string = String::from("Hello") + ", world!"; As a quick aside, in Rust, the :: syntax is called the “path separator” and is used to access items within a module, struct, or enum.