Some strange syntax

Could anybody help to explain some syntax?

The trait could be inherited?

pub trait ToSocketAddrs: sealed::ToSocketAddrsPriv {}

What does .. mean here?

            (&self[..]).to_socket_addrs()

That's the built in way to create a RangeFull.

0, 1, 2, 3, 4, 5, 6, 7
├────────────────────┤
         [..]

It's akin to

  • Range (2..4)
    0, 1, 2, 3, 4, 5, 6, 7
          ├──┤
         [2..4]
    
  • RangeFrom (2..)
    0, 1, 2, 3, 4, 5, 6, 7
          ├──────────────┤
               [2..]
    
  • RangeTo (..3)
    0, 1, 2, 3, 4, 5, 6, 7
    ├─────┤
     [..3]
    
  • RangeInclusive (2..=3)
    0, 1, 2, 3, 4, 5, 6, 7
          ├──┤
         [..=3]
    
  • RangeToInclusive (..=3)
    0, 1, 2, 3, 4, 5, 6, 7
    ├────────┤
      [..=3]
    

It's generally used as a kind of index. In this case it is, and it means to index all of the items in self.

Generally, RangeFull is replaced with just a borrow instead of an index since because of deref rules these two lines are equal:

let x: &[u8] = &my_vec[..];
let y: &[u8] = &my_vec;
3 Likes

Thanks. And I am also confused about || {} syntax?
What does it return? It's also associated with thread and generator.
And could the || use some arguments? i.e. |x, y|?

Why the official rust book do not mention such function literal?

How to identify the function as Fn, FnOnce or FnMut?

The rust book has a whole chapter on that:

https://doc.rust-lang.org/stable/book/ch13-01-closures.html

Thanks. I see now.

How about this? Anybody?

This is not an inheritance, although the concept is similar.

The syntax trait A: B is, in some sence, a sugar for trait A where Self: B. It means "this trait can be implemented only on types which also implement B". Sometimes it's useful to think other way round: "on every type implementing this trait, trait B will always be implemented to"; that's the reason why you can require T: A in generic function and then call methods of B.

In this case, this seems to be used as a small hack to achieve so-called "sealed trait" functionality. The sealed module is probably private, so the trait sealed::ToSocketAddrsPriv cannot be named by anyone outside the library, and hence cannot be implemented. As a result, it's impossible to implement ToSocketAddrs from outside, too - only the owner can do this.

Thanks. Why the rust book do not mention this topic?

Supertraits are covered later in The Book under "Advanced Features" - "Advanced Traits": Advanced Traits - The Rust Programming Language

2 Likes

Thanks. :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.