DEV Community

El Bruno for Microsoft Azure

Posted on • Originally published at on

#Rust 🦀 – Let’s create a Generic log() Function👍

Hi !

Let’s create a generic log function. This will not make a lot of sense, since the println! function already support lots of data types. However, this is a nice way to understand how generics works.

Here is the log function.

use std::fmt::Display;

// Generic Function to print data to the console
fn console_log<T: Display>(x: T) {
    println!("{}", x);

Enter fullscreen mode Exit fullscreen mode

The log function receives a parameter x, that support any type from Display, and then it prints the parameter to the console.

The following sample shows

  • Print a String
  • Print an Integer
  • Print a Struct, that implements a function to show the struct data

And the output is

output of the sample app<br>
Hello World<br>
Pet Name: Ace the Puppy - Age: 1

Source Code

Super cool !

Happy coding!


El Bruno

More posts in my blog

Top comments (0)