👉Impl Into | Rust

Will

Take this Function from my Sandbox Project:

(Check it out here: https://github.com/the-sandbox-project/sandbox)

Looks pretty good, a get_title function that takes a String as an argument and you guessed it, returns the title. If you thought that, you would be right!

Where the problem occurs is in debugging where I quickly need to use dummy data and do not want to use the to_string method constantly or worry about using a reference

The Solution 👀

The Impl Keyword! This way, you do not have to worry about what string you pass as long as it can convert to a string. The new code looks something like this:

To Note:

  1. id’s type has changed from String => impl Into<String> (turbofish’ can be any type you would like to infer to)
  2. id = id.into() | This makes the magic work and will change the inputted value into a String as long as it can be transformed into one

I’m Intrigued! But Why?

Readability & Convenience

By implementing into any type, you provide a concise and direct way to convert your types, in an easier fashion too!

Interoperability / Polymorphism & Abstraction

With Impl, you can improve your compatibility with other libraries and work on types that can be converted into a String (Also promotes code re-usability and avoids unnecessary duplication 😲).

Easier Data Transformation

Using Impl removes all the headaches you will have trying to convert different strings and worrying about lifetimes and things of that nature you just do not have time for

Have fun with this! 💫

No responses yet

Write a response