<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ankit</title>
    <description>The latest articles on DEV Community by Ankit (@jankit).</description>
    <link>https://dev.to/jankit</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1027838%2F191ecf45-5b68-4731-988d-a99fe5ba3eb7.png</url>
      <title>DEV Community: Ankit</title>
      <link>https://dev.to/jankit</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jankit"/>
    <language>en</language>
    <item>
      <title>From and Into Traits in Rust Programming Language</title>
      <dc:creator>Ankit</dc:creator>
      <pubDate>Thu, 16 Feb 2023 05:58:30 +0000</pubDate>
      <link>https://dev.to/intmain/from-and-into-traits-in-rust-programming-language-182p</link>
      <guid>https://dev.to/intmain/from-and-into-traits-in-rust-programming-language-182p</guid>
      <description>&lt;p&gt;If you are new to Rust then From (From) and Into (into) traits might sound confusing to you, but they are interesting trait systems of Rust. In this tutorial, we will learn From and Into traits with examples.&lt;/p&gt;

&lt;p&gt;The From and Into traits are inherently linked, and this is actually part of its implementation. If you are able to convert type A from type B, then it should be easy to believe that we should be able to convert type B to type A.&lt;/p&gt;

&lt;h2&gt;
  
  
  From Trait
&lt;/h2&gt;

&lt;p&gt;The From trait provides the ability to create a conversion trait, which allows you to convert values of one type into values of another type. For example, the standard library implements impl From&amp;lt;&amp;amp;'_ str&amp;gt; for String which allows you to generate a &lt;a href="https://intmain.co/string-in-rust-programming-language/"&gt;String&lt;/a&gt; from a &amp;amp;str.&lt;/p&gt;

&lt;p&gt;For example, we can easily convert a &lt;a href="https://intmain.co/string-in-rust-programming-language/"&gt;&amp;amp;str&lt;/a&gt; into a &lt;a href="https://intmain.co/string-in-rust-programming-language/"&gt;String&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let my_str = "Hello Intmain";
let my_string = String::from(my_str);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Another example of from trait:&lt;/p&gt;

&lt;p&gt;Suppose we want to implement our own From trait From for SplitName. This would allow us to split any given name separated by whitespace into Struct containing first and last names. This can be done easily using From trait. Below is an example of the same.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::convert::From;

#[derive(Debug)]
struct SplitName{
    first_name: String,
    last_name: String,
}
impl From&amp;lt;String&amp;gt; for SplitName {
    fn from(item: String) -&amp;gt; Self {

        let name_vector:Vec&amp;lt;&amp;amp;str&amp;gt; = item.split_whitespace().collect();
        SplitName { first_name : name_vector[0].to_string(), last_name :name_vector[1].to_string(), }
    }
}
fn main() {
    let from_example = SplitName::from("Int Main".to_string());
    println!("The name is {:?}", from_example);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The name is: SplitName { first_name: "Int", last_name: "Main" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The From is also very useful when performing error handling. When constructing a function that is capable of failing, the return type will generally be of the form Result.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; This trait must not fail. The From trait is intended for perfect conversions. If the conversion can fail or is not perfect, use &lt;a href="https://doc.rust-lang.org/std/convert/trait.TryFrom.html"&gt;TryFrom&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Into Trait
&lt;/h2&gt;

&lt;p&gt;The Into trait is the opposite of the From trait. The Implementation of From automatically provides the implementation of Into trait and one should avoid implementing Into trait and instead implement From trait.&lt;/p&gt;

&lt;p&gt;Using the Into trait will typically require specification of the type to convert into as the compiler is unable to determine this most of the time.&lt;/p&gt;

&lt;p&gt;For example, we can easily convert a &amp;amp;str into a String&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let my_str = "Hello Intmain";
let my_string :String = my_str.into();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Taking the above example again to split any given name separated by whitespace into Struct containing first and last names, we can split the name directly by calling the .into() to the given name after converting it into the &lt;a href="https://intmain.co/string-in-rust-programming-language/"&gt;string&lt;/a&gt;. Here we are required to provide the specification as:  let into_example :SplitName = "Int Main".to_string().into();&lt;/p&gt;

&lt;p&gt;Here’s the complete code to convert a name into SplitName using the From and Into traits:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use std::convert::From;

#[derive(Debug)]
struct SplitName{
    first_name: String,
    last_name: String,
}
impl From&amp;lt;String&amp;gt; for SplitName {
    fn from(item: String) -&amp;gt; Self {

        let name_vector:Vec&amp;lt;&amp;amp;str&amp;gt; = item.split_whitespace().collect();
        SplitName { first_name : name_vector[0].to_string(), last_name :name_vector[1].to_string(), }
    }
}
fn main() {
    let from_example = SplitName::from("Int Main".to_string());
    println!("The name is using from: {:?}", from_example);

    let into_example :SplitName = "Int Main".to_string().into();
    println!("TThe name is using into: {:?}", into_example);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Output&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;The name is using from: SplitName { first_name: "Int", last_name: "Main" } 
The name is using into: SplitName { first_name: "Int", last_name: "Main" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You’re free to use into() and from() both and it’s up to you to decide which one feels the most expressive to your code but prefers using Into over From when specifying trait bounds on a generic function to ensure that types that only implement Into can be used as well.&lt;/p&gt;

&lt;p&gt;**Note: **This trait must not fail. If the conversion can fail, use &lt;a href="https://doc.rust-lang.org/std/convert/trait.TryInto.html"&gt;TryInto&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The “From” and “Into” traits in Rust are used to perform type conversions. The “From” trait allows you to convert values of one type into values of another type by implementing the from method. The “Into” trait is a simplified version of the “From” trait and allows for a more straightforward conversion by implementing the into method.&lt;/p&gt;

&lt;p&gt;The main difference between the two is that the “Into” trait assumes that the conversion will always be successful, while the “From” trait allows for the possibility of a failed conversion, which is achieved by returning a Result type from the from method implementation, which can be either Ok with the converted value, or Err with an error description.&lt;/p&gt;




&lt;p&gt;This post was originally published at &lt;a href="https://intmain.co/from-and-into-in-rust-programming-language/"&gt;intmain.co&lt;/a&gt;&lt;/p&gt;

</description>
      <category>rust</category>
      <category>programming</category>
      <category>beginners</category>
      <category>codenewbie</category>
    </item>
  </channel>
</rss>
