Chapter 5 - Traits & Generics
-
Derive a debug trait to print info about your struct that contains
name
,c1ass
androll
. -
Create a generic function to get min of 2 values.
hint:
You might need to useOrd
trait bound. -
Implement custom
Drop
trait for a struct nameStudent
that contains yourname
,age
androll number
. It should returnRoll number <roll number> has name <name> with age <age> and is a <junior/senior>
. Being Junior or Senior depends on age (18 or above). -
Implement a custom
Debug
message for the above Struct. -
Implement custom
Iterator
trait for a struct namedGeometricSeries
that has 3 fieldsfirst_number
,current_number
andratio
of typei32
. The iterator should return the next 11 numbers in geometric progression.
hint:
Use.take(11)
to get the next 11 infor
loop. -
Implement the same as above for a
FibonacciSeries
struct. -
Implement a generic function name
sum
with additional parameter ofindex: usize
that can take eitherGeometricSeries
orFibonacciSeries
and returns the sum upto the given index.
hint:
useT: Iterator<Item = i32>
whereT
is generic -
Write a generic function name
Multiply
that multiplies allusize
,isize
andfsize
type values. -
Make a generic function to return the greater of the 2 given values (integer and floats).
-
Implement a trait named
Hello
with a default functionsay(&self)
that printsHello, <self>!
, Implement this forstr
andstring
without providing any definition ofHello
(simplyimpl Hello for str {}
) callsay
on strWorld
.