Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's a fairly complicated example. Let me deconstruct it:

In Rust you work a lot with types. You can write code that supports several different types but you usually have to specify which constraints these types have to fulfill. You specify these constraints between <> brackets. In this example we have 3 such constraints:

1) <'s, S: Seed, A: Copy>

2 & 3) <dyn Fn(S) -> Step<S, A> + 's>

with 2) <S, A>

with 3) <dyn Fn(S) -> Step<S, A> + 's>

Because these constraints are all part of the same struct definiton, the names in these 3 constraints refer to the same things. The names are: s, S, A

Constraints in Rust can either be lifetimes or traits (similar to interfaces in Java). Lifetimes are marked with a single quote (') followed by the name of the lifetime (in this case: 's)

Let's look at constraint number 1):

I) We declare a lifetime 's but we do not specify where it will be applied in the struct yet.

II) We declare a type constraint S. Every type that is used as S must implement the Seed trait.

III) We declare a type constraint A. Every type that is used as A must implement the Copy trait.

Before I go into constraint 2&3, I must explain that `Fn(S) -> Step<S, A> + 's>` describes the type signature of a closure. The syntax is basically `Fn(parameter-list) -> return-value`.

Constraint 2) says that the return value must be a struct `Step` with the type parameters `S` and `A`.

Constraint 3) says that the next field of the struct must be a `Box` that contains an object of unknown size (hence the `dyn`) which is a closure that takes one `S` parameter and returns a `Step` struct with the type parameters `S` and `A`. The lifetime of the closure must be `'s`.

Finally, the seed must be of type `S`.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: