Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Microsoft Azure profile imageEl Bruno
El Bruno forMicrosoft Azure

Posted on • Originally published atelbruno.com 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 consolefn console_log<T: Display>(x: T) {    println!("{}", x);}
Enter fullscreen modeExit 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>123<br>Pet Name: Ace the Puppy - Age: 1

Source Code

Super cool !

Happy coding!

Greetings

El Bruno

More posts in my blogElBruno.com.


Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Invent with purpose

Any language. Any platform.

More fromMicrosoft Azure

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp