Difference between traits and generics and difference b/w Generic functions and Traits

This may seem stupid and basic. But I am having a hard time distinguishing between these two concepts and their usage in rust. Mostly because they are always used together and also presented together most of the times ( like trait bounds and trait objects where both the concepts are used). I want to understand the exact demarcation between the two concepts. What can be called as a generic and what are traits?

A generic is an empty slot where you can put in a type. A trait is way to restrict which types fit into the empty slots (and by extension, a way to reuse code with many types).

fn my_generic_function<T: MyTrait>(t: T) {

In the example above, T is a generic parameter. When you call my_generic_function, you have to choose what T should be in that call. The MyTrait is a trait, which restricts which types you can choose for T.

A function or struct is generic when it has a generic parameter.

1 Like

can we implement Generic functions??/if so,why we need to go for Traits

When you implement a function (generic or not), you simply write the code inside the function. When you implement a trait on a type, you make that type usable in generic functions which require that trait.

// This defines a trait
trait MyTrait {
    fn name(&self) -> &str;
// This implements MyTrait on String
impl MyTrait for String {
    fn name(&self) -> &str {
// This defines a function. Since String implements MyTrait, you can use a String here:
fn my_func<T: MyTrait>(t: T) {
    // my_func has been implemented because I have written the code
    // inside it:
    println!("Name: {}", t.name());

When you implement a trait on a type, you make it possible to use that type with a generic function. Because my_func is generic, you can use it with any type that implements MyTrait, and you only have to write my_func once, even though there may be many types you can use it with.

1 Like

You may be familiar with C++ templates? In C++, you can use whatever functionality you want inside a template function and if you try to use something that doesn't exist you will get a call site failure even though the error originates inside the template. In Rust, when you write a generic function, you have to declare what functionality the types must have, or the function won't compile. The way a function declares what functionality its type parameters should have is by using trait bounds.