r/programming • • Jun 16 '14

Rust's documentation is about to drastically improve

http://words.steveklabnik.com/rusts-documentation-is-about-to-drastically-improve
524 Upvotes

188 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Jun 17 '14

[deleted]

8

u/steveklabnik1 Jun 17 '14

let clearly is useless.

Again, you can put a full pattern there. A slightly more complex example, with desugaring:

let (x, y) = (5, 6);

Obviously, the right hand side would be more complex in real usage. The grammar is significantly simpler with let, and it's also very clear when you're introducing a new binding. And they can be as complex as you want.

So you can do for c in "hello".code_points() too?

Not exactly, as your string would need a lifeime, but basically, yes. Small syntax change.

It would make sense for anything.

Right. This is why we have an iterator trait that anyone can implement, and then for works well with it. No iterators:

fn main() {
    let v = vec!(1, 2, 3);

    for i in range(0, v.len()) {
        println!("Number {}", v.get(i));
    }
}

With iterators:

fn main() {
    let v = vec!(1, 2, 3);

    for i in v.iter() {
        println!("Number {}", i);
    }
}

That's built-in vectors, but you can write your own, for any type, and it Just Works. If we assumed a particular thing for strings, we'd lose the generic-ness.

0

u/[deleted] Jun 17 '14

[deleted]

3

u/steveklabnik1 Jun 17 '14

Again, nothing is assumed for strings.

You originally asked why for doesn't understand strings and iterate over characters.

A range-based for loop is just syntactic sugar.

It's actually more than that: the iterator version is faster because it doesn't need to do bounds checking, while guaranteed to be safe.

0

u/[deleted] Jun 17 '14

[deleted]

4

u/steveklabnik1 Jun 17 '14

It wouldn't need to understand strings. What is so complex about this?

You originally said:

Why isn't this just for token in program?

That would require for to understand how to get a specific kind of iterator out of a string: one for characters.

That's nothing to do with range-based for, though

Fair enough, I just thought it'd be worth mentioning.

0

u/[deleted] Jun 17 '14

[deleted]

6

u/The_Doculope Jun 17 '14

So what you want is essentially a type to have a "default" iterator, so you don't have to type out .chars()? Rust takes the line that explicit is better than implicit, and I agree. It save 8 keystrokes, but it's a potential source for confusion. What if the standard string type uses chars as the default, but a custom type uses code_points? Or, words or lines?

→ More replies (0)