Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Rust Generics and Traits

Rust Generics and Traits

Generics are an indispensable mechanism in a programming language.

In C++, "templates" are used to implement generics, while the C language has no generics mechanism, which makes it difficult for C to build projects with complex types.

The generics mechanism is used by programming languages to express type abstraction; it is generally used for classes whose functionality is fixed but whose data types are to be determined, such as linked lists, maps, etc.

Defining generics in functions

This is a selection-sort method for integer numbers:

Example

fn

 max

(

array

:

 

&

[

i32

]

)

 

->

 

i32

 

{

    

let

 

mut

 max_index 

=

 

0

;

    

let

 

mut

 i 

=

 

1

;

    

while

 i 

<

array.len

(

)

{

if

array

[

i

]

array

[

max_index

]

{

max_index

=

i

;

        

}

        i 

+=

 

1

;

    

}

    array

[

max_index

]

}

fn

 main

(

)

 

{

    

let

 a 

=

 

[

2

,

 

4

,

 

6

,

 

3

,

 

1

]

;

    println

!

(

"max = {}"

,

 max

(

&

a

)

)

;

}

Running result:

max = 6

This is a simple program for taking the maximum value, which can handle data of the i32 numeric type, but cannot be used for f64 data. By using generics we can make this function usable with various types. But in fact not all data types can be compared in size, so the next piece of code is not meant to be run, but to describe the syntax format of function generics:

Example

fn

 max

<

T

(

array

:

 

&

[

T

]

)

 

->

 T 

{

    

let

 

mut

 max_index 

=

 

0

;

    

let

 

mut

 i 

=

 

1

;

    

while

 i 

<

array.len

(

)

{

if

array

[

i

]

array

[

max_index

]

{

max_index

=

i

;

        

}

        i 

+=

 

1

;

    

}

    array

[

max_index

]

}

Generics in structs and enums

The Option and Result enums we learned about earlier are generic.

Both structs and enums in Rust can implement the generics mechanism.

struct Point {

    x: T,

    y: T

}

This is a point-coordinate struct, where T represents the numeric type describing the point's coordinates. We can use it like this:

let p1 = Point {x: 1, y: 2};

let p2 = Point {x: 1.0, y: 2.0};

No type is declared when using it; here the automatic type mechanism is used, but type mismatches are not allowed, as follows:



let p = Point {x: 1, y: 2.0};

When x is bound to 1, T is already set to i32, so an f64 type is not allowed. If we want x and y to be represented by different data types, we can use two generic identifiers:



struct Point {

    x: T1,

    y: T2

}

Ways to express generics in enums include Option and Result:



enum Option {

    Some(T),

    None,

}



enum Result {

    Ok(T),

    Err(E),

}

Both structs and enums can define methods, so methods should also implement the generics mechanism, otherwise a generic class cannot be operated on by effective methods.

Example

struct

Point

<

T

{

x

:

T

,

    y

:

T

,

}

impl

<

T

Point

<

T

{

fn

x

(

&

self

)

->

&

T

{

&

self

.x

}

}

fn

main

(

)

{

let

p

=

Point

{

x

:

1

,

y

:

2

}

;

    println

!

(

"p.x = {}"

,

p.x

(

)

)

;

}

Running result:



p.x = 1

Note that after the impl keyword there must be , because the T that follows it takes it as a model. But we can also add methods for one of the generic types:



impl Point {

    fn x(&self) -> f64 {

        self.x

    }

}

The generics of the impl block itself do not prevent its internal methods from having generics:

impl Point {

    fn mixup(self, other: Point) -> Point {

        Point {

            x: self.x,

            y: other.y,

        }

    }

}

The method mixup merges the x of a Point point with the y of another Point point into a new point whose type is Point.


Feature

The concept of a trait is close to an interface (Interface) in Java, but the two are not completely identical. What traits and interfaces have in common is that both are a kind of behavioral specification that can identify which classes have which methods.

Traits are represented in Rust by trait:

trait Descriptive {

    fn describe(&self) -> String;

}

Descriptive stipulates that implementors must have a describe(&self) -> String method.

We use it to implement a struct:

Example

struct

Person

{

    name

:

String

,

    age

:

u8

}

impl

Descriptive

for

Person

{

   

fn

describe

(

&

self

)

->

String

{

        format

!

(

"{} {}"

,

self

.name

,

self

.age

)

   

}

}

The format is:



impl <特性名> for <所实现的类型名>

In Rust the same class can implement multiple traits, but each impl block can implement only one.

Default traits

This is where traits differ from interfaces: an interface can only specify methods but not define them, while a trait can define a method as a default method. Because it is "default", an object can either redefine the method or not redefine it and use the default one:

Example

trait

Descriptive

{

   

fn

describe

(

&

self

)

->

String

{

        String

::

from

(

"[Object]"

)

   

}

}

struct

Person

{

    name

:

String

,

    age

:

u8

}

impl

Descriptive

for

Person

{

   

fn

describe

(

&

self

)

->

String

{

        format

!

(

"{} {}"

,

self

.name

,

self

.age

)

   

}

}

fn

main

(

)

{

   

let

cali

=

Person

{

        name

:

String

::

from

(

"Cali"

)

,

        age

:

24

   

}

;

    println

!

(

"{}"

,

cali.describe

(

)

)

;

}

Running result:

Cali 24

If we remove the contents of the impl Descriptive for Person block, the result will be:



[Object]

Traits as parameters

In many cases we need to pass a function as a parameter, such as a callback function or setting a button event. In Java a function must be passed as a class instance implementing an interface; in Rust this can be achieved by passing a trait parameter:

fn output(object: impl Descriptive) {

    println!("{}", object.describe());

}

Any object that implements the Descriptive trait can be an argument to this function. The function does not need to know whether the passed object has other properties or methods; it only needs to know that it definitely has the methods specified by the Descriptive trait. Of course, other properties and methods cannot be used inside this function.

Trait parameters can also be implemented with this equivalent syntax:

fn output(object: T) {

    println!("{}", object.describe());

}

This is a kind of syntactic sugar styled like generics, which is very practical when multiple parameter types are all traits:



fn output_two(arg1: T, arg2: T) {

    println!("{}", arg1.describe());

    println!("{}", arg2.describe());

}

When a trait used as a type involves multiple traits, you can use the + symbol, for example:

fn notify(item: impl Summary + Display)

fn notify(item: T)

**Note:** This is only for representing types; it does not mean it can be used in an impl block.

Complex implementation relationships can be simplified with the where keyword, for example:

fn some_function(t: T, u: U)

can be simplified to:

fn some_function(t: T, u: U) -> i32

    where T: Display + Clone,

          U: Clone + Debug

After understanding this syntax, the "maximum value" example from the generics chapter can actually be implemented:

Example

trait

Comparable

{

   

fn

compare

(

&

self

,

object

:

&

Self

)

->

i8

;

}

fn

max

<

T

:

Comparable

(

array

:

&

[

T

]

)

->

&

T

{

   

let

mut

max_index

=

0

;

   

let

mut

i

=

1

;

   

while

i

<

array.len

(

)

{

if

array

[

i

]

.compare

(

&

array

[

max_index

]

)

0

{

max_index

=

i

;

       

}

        i

+=

1

;

   

}

   

&

array

[

max_index

]

}

impl

Comparable

for

f64

{

   

fn

compare

(

&

self

,

object

:

&

f64

)

->

i8

{

       

if

&

self

&

object

{

1

}

       

else

if

&

self

==

&

object

{

0

}

       

else

{

1

}

   

}

}

fn

main

(

)

{

   

let

arr

=

[

1.0

,

3.0

,

5.0

,

4.0

,

2.0

]

;

    println

!

(

"maximum of arr is {}"

,

max

(

&

arr

)

)

;

}

Running result:



maximum of arr is 5

Tip: Since the second parameter of the compare function must be declared to be the same as the type implementing the trait, the Self keyword (mind the capitalization) represents the current type (not an instance) itself.

Traits as return values

The format for a trait as a return value is as follows:

Example

fn

person

(

)

->

impl

Descriptive

{

    Person

{

        name

:

String

::

from

(

"Cali"

)

,

        age

:

24

   

}

}

But there is one point: a trait used as a return value only accepts objects that implement that trait as return values, and all possible return types within the same function must be exactly the same. For example, struct A and struct B both implement trait Trait, so the following function is wrong:

Example

fn

some_function

(

bool

bl

)

->

impl

Descriptive

{

   

if

bl

{

       

return

A

{

}

;

   

}

else

{

       

return

B

{

}

;

   

}

}

Conditional method implementation

impl is very powerful; we can use it to implement methods for a class. But for a generic class, sometimes we need to distinguish the methods already implemented by its generics to decide the methods it should implement next:

struct A {}



impl A {

    fn d(&self) {}

}

This code declares that A type can only validly implement this impl block under the condition that T has already implemented the B and C traits.