What [..1] means

What does this mean? I`m a beginner.

[..1]

A task was on codewars: "You ask a small girl,"How old are you?" She always says, "x years old", where x is a random number between 0 and 9.
Write a program that returns the girl's age (0-9) as an integer.
Assume the test input string is always a valid string. For example, the test input may be "1 year old" or "5 years old". The first character in the string is always a number."

And i found a solution

fn get_age(age: &str) -> u32 {
    age[..1].parse().unwrap()
}

To answer your question, that's actually 2 pieces of syntax:

  1. ..1 is a piece of syntax that can be used to create a value of type std::ops::RangeTo.
    The range ..1 means "everything up to but not including 1", so in this case it's the same as just the 0-th element.

  2. &foo[..1] slices foo, meaning it returns the subslice indicated by the range.

So taken together it just returns the first char in the string. Note that that may not be what you want: In particular, if you want e.g. ë to count as one "character" then you'd be better off using unicode_segmentation::UnicodeSegmentation to iterate over the string.

1 Like

It takes up to but not including the 1st byte of the string (this is the leading byte, as indexing starts at 0).

2 Likes

That is not correct. The type created is std::ops::RangeTo in this case. More precisely it's RangeTo<usize>. (Playground)

Both std::ops::Range and std::ops::RangeTo implement the same trait, which is std::ops::RangeBounds.

4 Likes

@murawum note that the clarification between bytes and chars is very relevant: str slicing works on byte indices, but if you try to create a subslice that isn't valid UTF8, it will panic. So if the first character of the String isn't ASCII, the example will panic.

Now, Codewars said

The first character in the string is always a number

And given the nature of such online practice/competition platforms, you can safely assume in this case they meant an ASCII digit when they said number. However, be aware that this doesn't reflect how a production-worthy program would work at all (as those would handle malformed inputs), and take care not to build any bad habits.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.