And back to traits we go...

The simplest way to think of a trait is that it creates a signature to the implementation. If you're used to C (or C++), then you will have seen this in code akin to this:

// mylib.h 
int myFunction(int a, int b, float c);

// mylib.c
#include "mylib.h"
int myFunction(int a, int b, float c)
{
// implement the code
return some_value;
}

// myotherfile.c
#include "mylib.h"
int some_function()
{
int value = myFunction(1, 2, 3.14f);
return value;
}

The compiler accepts this code is correct as there is a signature in the .h file that says somewhere there is a compiled function that provides the implementation of this call. When the compiler comes to link everything together, the code that was promised by the signature is found and myFunction does whatever it's supposed to do and returns the int.

In C#, this would be supplied via an interface.

With Rust, we have something very similar.

The trait supplies the signature, the impl supplies the implementation, and the code calls the impl.

Now this may seem somewhat like overkill. Why would you create a stub when the implementation is typically in the same source file? The answer is we can use traits in a Rust library known as a crate. The trait tells the compiler that somewhere the code is implemented and it will be linked at the last stage of the build.

We will look at crates in the next chapter.

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

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