What's the big deal? That was simple enough!

While on the face of it, using an external library via FFI is not rocket science, it does come with a number of issues. Why do we need to annotate blocks with unsafe even when we are referring to known names in libraries?

As we have seen time and again with Rust, the compiler does an awful lot for the developer that you won't see in many other compilers. It ensures thread safety, that a particular operation can be achieved, the buffers don't overrun, that we don't leave memory unallocated or attempt to deallocate twice, and plenty of other things that ensure that, as far as possible, the code we have will run and remain rock-solid (in terms of reliability).

Unfortunately, with external libraries, all the compiler can do is to expect something from a linked library. Threads may be left hanging or be plain unsafe; there is no guarantee that if I passed in 6 and 0 for a similar division function, what is returned is a number and pretty much anything else can go wrong.

By using unsafe, we give the compiler a promise that when it links the code, what it links to will be bound correctly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset