Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - What does the "two periods" operator mean in the context of a subscript inside of square brackets?

I was looking through Rust's source code to better acquaint myself with the language. I came across this snippet.

// Collect program arguments as a Vec<String>.
let cmd: Vec<_> = env::args().collect();

// Some unrelated code omitted here.

match subcommand::parse_name(&cmd[1][..]) {
    // It did some stuff here.
}

I didn't understand the [..]. So, I went and checked out the declaration of parse_name:

pub fn parse_name(name: &str) -> Option<Box<Subcommand>>

It's what I expected, but I still don't get the [..]. What does it mean in this context? Isn't it just passing the first String in cmd as a &str? If so, is this equivalent to just writing cmd[1]? Why did they do it this way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two periods (..) is the range operator. You can find this in the Operators and Symbols Appendix of the Rust book. There are six flavors:

  1. Range: 1..10
  2. RangeFrom: 1..
  3. RangeTo: ..10
  4. RangeFull: ..
  5. RangeInclusive: 1..=10
  6. RangeToInclusive: ..=10

When no item occupies an end position, the range goes on "forever" in that direction.

This combines with the Index trait (or IndexMut, if mutation is required). In your example, you have a string slice (kind of, see next point) that you are applying indexing to: "foo"[2..].

Specifically, &str implements Index as

Returns a slice of the given string from the byte range

Then there's a third bit of ergonomics happening: Deref (or DerefMut in similar cases). String implements Deref by returning a &str, so any method available to a &str is available to a String.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...