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

DISCLAIMER: I'm not well-versed in type theory at all, so take my words with a grain of salt.

Unfortunately I haven't seen any comprehensive article that discusses affine types in terms of Rust. So I can't recommend a link to you, instead I'll try to explain them in my own words.

Affine types are those whose values can only be used at most once. They are implemented in Rust as ownership and borrowing. In my example above, `send_header` borrows the `conn` variable, whereas `send_body` takes the ownership of the `conn` variable. As you lost the ownership of `conn`, you cannot use it anymore, thus resulting in a compile error.

This is similar to C++'s move semantics, where you are not permitted to move the same value more than once. It is just that in C++ "move only once" is a convention, whereas in Rust it is enforced by the type system.

In Rust, if you pass an argument by value, you're automatically using affine types. You cannot use the passed variable anymore. To "borrow" instead, you need to opt-out using references. So, the hypothetical API I mentioned above would be written as:

  fn send_header(&self, text: &str) { ... }
  fn send_body(self, text: &str) { ... }
Note the difference of `&`.

Finally, all of these aren't just hypothetical. The exactly same design is used in Hyper[1], which is an HTTP library, and in nickel[2], which is a web framework in Rust. If you look at the API doc you will see there is no '&' in the self parameter. That means it's passed by value, using affine types, and the ownership is transferred, so you cannot use the original variable anymore.

I hope this helps.

[1] http://hyper.rs/hyper/hyper/client/struct.RequestBuilder.htm...

[2] http://docs.nickel.rs/nickel/struct.Response.html#method.sen...



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

Search: