{"id":3049,"date":"2022-07-25T08:33:44","date_gmt":"2022-07-25T13:33:44","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=3049"},"modified":"2022-08-28T10:51:36","modified_gmt":"2022-08-28T15:51:36","slug":"rust-clone-vs-to_owned","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/","title":{"rendered":"Rust | The Difference Between .clone() and .to_owned()"},"content":{"rendered":"\n<p>Chances are you recently came across the definition of the <a href=\"https:\/\/doc.rust-lang.org\/std\/borrow\/trait.ToOwned.html#tymethod.to_owned\" target=\"_blank\" rel=\"noopener\">ToOwned<\/a> trait to realize it is <em>a generalization of the <a href=\"https:\/\/doc.rust-lang.org\/std\/clone\/trait.Clone.html\" target=\"_blank\" rel=\"noopener\">Clone<\/a> <\/em>trait? If so, what is the difference between the two traits? more specifically, what is the difference between <code>.clone()<\/code> and <code>.to_owned()<\/code> if they work the same?<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>A generalization of Clone to borrowed data.<\/p><cite>https:\/\/doc.rust-lang.org\/std\/borrow\/trait.ToOwned.html#tymethod.to_owned<\/cite><\/blockquote>\n\n\n\n<p><strong>The difference between <code>.clone()<\/code> and <code>.to_owned()<\/code> occurs when applying either of the two methods on slices such as string slice <code>&amp;str<\/code> or arrays with undefined capacity like  <code>&amp;[i8]<\/code> or <code>&amp;[u32]<\/code><\/strong>,<strong> in their borrowed state (<code>&amp;T<\/code>)<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><code>.clone()<\/code>  generates a duplicate of types such as<code>&amp;str<\/code> or  <code>&amp;[u8]<\/code> with the same type in its borrowed state (<code>&amp;T<\/code>). This means using <code>.clone()<\/code> on <code>&amp;str<\/code> and <code>&amp;[u8]<\/code> will generate <code>&amp;str<\/code> and <code>[u8]<\/code> respectively.<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let str = \"a\"; \/\/ type &amp;str \nlet cloned_str = str.clone(); \/\/ type &amp;str\n\nlet array:&amp;&#91;u8] = &amp;&#91;1, 2, 3];\n \/\/ type &amp;&#91;u8]\nlet cloned_array = array.clone(); type &amp;&#91;u8]<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong><code>.to_owned()<\/code> generates a duplicate of types such as <code>&amp;str<\/code> or <code>&amp;[u8]<\/code> with types that have ownership. This means using <code>.to_owned()<\/code> on <code>&amp;str<\/code> and <code>&amp;[u8]<\/code> will generate a <code>String<\/code> and a <code>Vec&lt;u8&gt;<\/code> respectively.<\/strong><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let array:&amp;&#91;u8] = &amp;&#91;1, 2, 3];\nlet cloned_array = array.to_owned();<\/code><\/pre>\n\n\n\n<p>You probably had to read twice the previous answer to understand the difference between <code>.clone()<\/code> and <code>.to_owned()<\/code>.  In fact, it might still not be clear the difference.<\/p>\n\n\n\n<p>Don&#8217;t worry. <\/p>\n\n\n\n<p>This article will explain with examples the difference between <code>.clone()<\/code> and <code>.to_owned()<\/code> methods. You will get an overall understanding of how each method works. Then, you will understand why <code>.to_owned()<\/code> generates a <code>String<\/code>  from a <code>&amp;str<\/code> .<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Understanding_more_about_the_clone_method\" >Understanding more about the .clone() method<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Accessible_with_the_Clone_trait\" >Accessible with the Clone trait<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Generating_a_duplicate_with_the_same_type\" >Generating a duplicate with the same type<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Generates_a_duplicate_of_T_as_T_for_scalar_types_and_tuples\" >Generates a duplicate of &amp;T as T for scalar types and tuples<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Generates_a_duplicate_of_T_as_T_for_arrays_with_a_defined_length\" >Generates a duplicate of &amp;[T] as [T] for arrays with a defined length<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#The_clone_not_go_from_T_to_T_on_arrays_without_a_specified_capacity\" >The .clone() not go from &amp;[T] to [T] on arrays without a specified capacity<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Understanding_more_about_the_to_owned_method\" >Understanding more about the .to_owned() method<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#The_to_owned_method_generates_a_String_from_str\" >The .to_owned() method generates a String from  &amp;str<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#The_to_owned_method_generates_a_Vector_from_a_reference_array_with_undefined_capacity\" >The .to_owned() method generates a Vector from a reference array with undefined capacity<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_more_about_the_clone_method\"><\/span>Understanding more about the <code>.clone()<\/code> method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>As the name suggests, the <code>.clone()<\/code> method generates a duplicate of an object similar to <a href=\"https:\/\/doc.rust-lang.org\/std\/marker\/trait.Copy.html\" target=\"_blank\" rel=\"noopener\">the <code>Copy<\/code> trait<\/a>. <strong>The difference between <code>Copy<\/code> and <code>Clone<\/code> is that <code>Copy<\/code> duplicates bits stored in the stack, while <code>Clone<\/code> might involve copying heap data<\/strong>, which could or not result in a more expensive operation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Accessible_with_the_Clone_trait\"><\/span>Accessible with the <code>Clone<\/code> trait<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>.clone()<\/code> method is available to all types deriving the <a href=\"https:\/\/doc.rust-lang.org\/std\/clone\/trait.Clone.html\" target=\"_blank\" rel=\"noopener\"><code>Clone<\/code> trait<\/a>. By default, all the primitive types (<code>str<\/code>, <code>i8<\/code>,<code>u8<\/code>, <code>char<\/code>,<code>array<\/code>, <code>bool<\/code>, etc), have access to the <code>.clone()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>    let str = \"a\";\n    let cloned_str = str.clone();\n\n    let number: u8 = 10;\n    let cloned_number = number.clone();\n\n    let borrowed_number:&amp;u8 = &amp;10;\n    let cloned_borrowed_number = borrowed_number.clone();\n\n    let array: &#91;&amp;str; 3] = &#91;\"a\", \"b\", \"c\"];\n    let cloned_array = array.clone();\n\n    let borrowed_array: &amp;&#91;&amp;str; 3] = &amp;&#91;\"a\", \"b\", \"c\"];\n    let cloned_borrowed_array = borrowed_array.clone();\n\n    let string: String = String::from(\"Hello, world!\");\n    let cloned_string = string.to_owned();<\/code><\/pre>\n\n\n\n<p>If you are defining a struct and want to have access the <code>.clone()<\/code> method, you must make sure:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Every field in the struct is clonable<\/li><li>To Add the <code>Clone<\/code> derive attribute  <\/li><\/ol>\n\n\n\n<p>To make this clear, if you create a <code>MyObject<\/code> struct like the following:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>struct MyObject {\n    first_name: String,\n    last_name: String,\n    age: u8,\n}\n\nimpl MyObject {\n    pub const fn new() -&gt; MyObject {\n        MyObject {\n            first_name: String::new(),\n            last_name: String::new(),\n            age: 0,\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p>and later in your code you decide to create a variable storing an <code>MyObject<\/code> data type,<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_object = MyObject::new();<\/code><\/pre>\n\n\n\n<p>you won&#8217;t have access to the <code>.clone()<\/code> method. Hence, <code>my_object<\/code> variable won&#8217;t have <code>.clone()<\/code> method and it will throw the following error if you attempt to use it.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>\/\/ this will throw the following error:\n\/\/ error&#91;E0599]: no method named `clone` found for struct `MyObject` in the current scope\nlet cloned_my_object = my_object.clone(); <\/code><\/pre>\n\n\n\n<p>To solve this issue, adding the <code>Clone<\/code> derive in the <em>struct<\/em> <code>MyObject<\/code> <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>#&#91;derive(Clone)]\nstruct MyObjectOne {\n    first_name: String,\n    last_name: String,\n    age: u8,\n}<\/code><\/pre>\n\n\n\n<p>will give access to the .clone() method:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_object = MyObject::new();\nlet cloned_my_object = my_object.clone(); \/\/ this will work!<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Generating_a_duplicate_with_the_same_type\"><\/span>Generating a duplicate with the same type<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>.clone()<\/code> generates a duplicate of an object <code>T<\/code> with the same type <code>T<\/code>, meaning if <\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>a is <code>u8<\/code>, the duplicate will be a <code>u8<\/code><\/li><li>a is <code>String<\/code>, the duplicate will be a <code>String<\/code><\/li><li>a is <code>&amp;[&amp;str]<\/code>, the duplicate will be a <code>&amp;[&amp;str]<\/code><\/li><li>a is <code>MyObject<\/code>,  the duplicate will be a <code>MyObject<\/code><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>    let number:u8 = 10; \/\/ type u8\n    let cloned_number = number.clone(); \/\/ type u8\n\n    let array: &amp;&#91;&amp;str] = &amp;&#91;\"a\", \"b\", \"c\"]; \/\/ type &amp;&#91;&amp;str]\n    let cloned_array = array.clone(); \/\/ type &amp;&#91;&amp;str]\n\n    let string: String = String::from(\"Hello, world!\"); \/\/ type String\n    let cloned_string = string.to_owned(); \/\/ type String\n\n    let my_object = MyObject::new(); \/\/ type MyObject\n    let cloned_my_object = my_object.clone(); \/\/ type MyObject<\/code><\/pre>\n\n\n\n<p>It is possible to duplicate values with known size at compile time in their borrowed state <code>&amp;T<\/code> to generate a duplicate in the owned state <code>T<\/code> using the <code>.clone()<\/code> method. <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>    let borrowed_number: &amp;u8 = &amp;10; \/\/ type &amp;u8\n    let cloned_borrowed_number = borrowed_number.clone(); \/\/ type u8\n\n    let borrowed_array: &amp;&#91;&amp;str; 3] = &amp;&#91;\"a\", \"b\", \"c\"]; \/\/ type &amp;&#91;&amp;str; 3]\n    let cloned_borrowed_array = borrowed_array.clone(); \/\/ type &#91;&amp;str; 3]\n\n    let string: &amp;String = &amp;String::from(\"Hello, world!\"); \/\/ type &amp;String\n    let cloned_string = string.clone(); \/\/ type String<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Generates_a_duplicate_of_T_as_T_for_scalar_types_and_tuples\"><\/span>Generates a duplicate of <code>&amp;T<\/code> as <code>T<\/code> for scalar types and tuples<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Rust has four primary scalar types:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Integers<\/li><li>Floating-point numbers<\/li><li>Booleans<\/li><li>Characters<\/li><\/ul>\n\n\n\n<p>They represent a single value. This means all integers (<code>12<\/code>), floating-point numbers (<code>3.4<\/code> ), booleans ( <code>true<\/code>,<code>false<\/code> ), and characters (<code>'a'<\/code>, <code>'z'<\/code>) have the same value no matter how many times you use them. It is because of this, that it makes it possible to generate an owned  duplicate from a borrowing state. In other words, going from <code>&amp;T<\/code> to <code>T<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let integer: &amp;u8 = &amp;1; \/\/ type is &amp;u8\nlet cloned_integer = integer.clone(); \/\/ type is u8\n\nlet floating_number = &amp;2.3; \/\/ type is &amp;f64\nlet cloned_floating_number = floating_number.clone(); \/\/ type is f64\n\nlet boolean = &amp;true; \/\/ type is &amp;boolean\nlet cloned_boolean = boolean.clone(); \/\/ type is boolean\n\nlet character = &amp;'a'; \/\/ type is &amp;char\nlet cloned_character = character.clone(); \/\/ type is char<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Generates_a_duplicate_of_T_as_T_for_arrays_with_a_defined_length\"><\/span>Generates a duplicate of <code>&amp;[T]<\/code> as <code>[T]<\/code> for arrays with a defined length<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The <code>.clone()<\/code> method can duplicate of array when the original array has ownership, meaning going from <code>[T]<\/code> to <code>[T]<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let owned_array: &#91;i32; 3] = &#91;1, 2, 3];\nlet cloned_owned_array = owned_array.clone(); \/\/ type is &#91;i32; 3]<\/code><\/pre>\n\n\n\n<p>However, <code>.clone()<\/code> can also go from <code>&amp;[T]<\/code> to <code>[T]<\/code> as long as the array capacity is defined. <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let borrowed_array: &amp;&#91;i32; 3] = &amp;&#91;1, 2, 3];\nlet cloned_borrowed_array = borrowed_array.clone(); \/\/ type is &#91;i32; 3]<\/code><\/pre>\n\n\n\n<p>The array capacity will also be implicitly defined even when you don&#8217;t assign a type definition (<code>&amp;[T]<\/code>). In the following example, the duplicate generated is  <code>[T]<\/code> from <code>[T]<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let borrowed_array = &amp;&#91;1, 2, 3]; \/\/ it will implicitly define the type as &amp;&#91;i32; 3]\nlet cloned_borrowed_array = borrowed_array.clone(); \/\/ type is &#91;i32; 3]<\/code><\/pre>\n\n\n\n<p>However, if you define the type is of variable is an array without explicitly defining the capacity, <code>.clone()<\/code> will still generate a duplicate. However, this new duplicate will be still in a borrowing state. Hence, it will go from  <code>&amp;[T]<\/code> to <code>&amp;[T]<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_clone_not_go_from_T_to_T_on_arrays_without_a_specified_capacity\"><\/span>The <code>.clone()<\/code> not go from <code>&amp;[T]<\/code> to <code>[T]<\/code> on arrays without a specified capacity<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>If you define the type of variable is an array without explicitly defining its capacity, <code>.clone()<\/code> will still generate a duplicate. However, this new duplicate will be still in a borrowing state. Hence, it will go from <code>&amp;[T]<\/code> to <code>&amp;[T]<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let numbers: &amp;&#91;i32] = &amp;&#91;1, 2, 3];\nlet cloned_numbers = numbers.clone(); \/\/ type is &#91;&amp;i32]\n\nlet strs: &amp;&#91;&amp;str] = &amp;&#91;\"asfa\", \"saf\", \"asfas\"];\nlet cloned_strs = strs.clone(); \/\/ type is &amp;&#91;&amp;str]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_more_about_the_to_owned_method\"><\/span>Understanding more about the <code>.to_owned()<\/code> method<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>As the Rust documentation states, the <code>.to_owned()<\/code> method is a generalization of the <code>Clone<\/code> trait to borrowed data. This means<strong>, <code>.to_owned()<\/code> generates a duplicate value.<\/strong> Hence, if you apply <code>.to_owned()<\/code> on <code>T<\/code> , the duplicate will be <code>T<\/code>  .<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let number:u8 = 10; \/\/ type u8\nlet to_owned_number = number.to_owned(); \/\/ type u8\n\nlet string: String = String::from(\"Hello, world!\"); \/\/ type String\nlet to_owned_string = string.to_owned(); \/\/ type String\n\nlet my_object = MyObject::new(); \/\/ type MyObject\nlet to_owned_my_object = my_object.to_owned(); \/\/ type MyObject<\/code><\/pre>\n\n\n\n<p>One key aspect of <code>.to_owned()<\/code> is that this method is capable of constructing owned data from any borrow of a given type. This means, if you apply <code>.to_owned()<\/code> on any <code>&amp;T<\/code>, the duplicate will be <code>T<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let number: &amp;u8 = &amp;10; \/\/ type u8\nlet cloned_number = number.to_owned(); \/\/ type u8\n\nlet string: &amp;String = &amp;String::from(\"Hello, world!\"); \/\/ type &amp;String\nlet cloned_string = string.to_owned(); \/\/ type String\n\nlet my_object: &amp;MyObject = &amp;MyObject::new(); \/\/ type &amp;MyObject\nlet cloned_my_object = my_object.to_owned(); \/\/ type MyObject<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_to_owned_method_generates_a_String_from_str\"><\/span>The <code>.to_owned()<\/code> method generates a <code>String<\/code> from  <code>&amp;str<\/code> <span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>One question that comes for many Rust developers is: <em>How come the <code>.clone()<\/code> method generates a similar data type when cloning a string slice reference (<code>&amp;str<\/code>) and the <code>.to_owned()<\/code> method<\/em> <em>generates a <code>String<\/code>? <\/em><\/p>\n\n\n\n<p>To answer this question, you must understand the concepts of <a href=\"https:\/\/doc.rust-lang.org\/book\/ch04-00-understanding-ownership.html\" target=\"_blank\" rel=\"noopener\">ownership and borrowing<\/a>. The string slice reference <code>&amp;str<\/code> is in its borrowed state. That means, that whichever variable stores the string slice reference does not own the value.<\/p>\n\n\n\n<p>In the previous section you learned the <code>.clone()<\/code> method can still convert from <code>&amp;T<\/code> to <code>T<\/code> where <code>T<\/code> could be a <a href=\"https:\/\/doc.rust-lang.org\/rust-by-example\/primitives.html\" target=\"_blank\" rel=\"noopener\">primitive type such as a boolean or a number<\/a> or a custom struct such as <code>MyObject<\/code>. What is the difference with a <code>str<\/code>? <\/p>\n\n\n\n<p>The string slice is not a primitive type but a sequence of characters. In other words, an array of characters <code>[T]<\/code>. A characteristic of <a href=\"https:\/\/doc.rust-lang.org\/book\/ch04-03-slices.html#the-slice-type\" target=\"_blank\" rel=\"noopener\">the string slice is that doesn&#8217;t have ownership<\/a>. The <code>.clone()<\/code> method attempts to make it possible to go from borrowed to owned, but that doesn&#8217;t mean always happens. As you know, that&#8217;s the case of the string slice reference <code>&amp;str<\/code> .<\/p>\n\n\n\n<p>Hence, the <code>.clone()<\/code> method does generate a duplicate of a string slice reference without ownership. That&#8217;s where the <code>.to_owned()<\/code> method differs from <code>.clone()<\/code>. <\/p>\n\n\n\n<p><a href=\"https:\/\/doc.rust-lang.org\/stable\/std\/borrow\/trait.ToOwned.html\" target=\"_blank\" rel=\"noopener\">The <code>.to_owned()<\/code> &#8220;generalizes&#8221; the <code>Clone<\/code> trait to construct data from borrow of a give type<\/a>. This implies that the core functionality of <code>to_owned()<\/code> is to make sure the duplicate value will always have ownership, even if this means having to allocate the values in a data type different from the original.<\/p>\n\n\n\n<p>By generating a <code>String<\/code> from a string slice reference <code>&amp;str<\/code> , <code>to_owned()<\/code> meats the criteria of providing ownership. As you should remember, a <code>String<\/code> value can have ownership. If you look at the definition of the  <code>String<\/code>, you will find it is a struct based on a vector.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>pub struct String {\n    vec: Vec&lt;u8&gt;\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_to_owned_method_generates_a_Vector_from_a_reference_array_with_undefined_capacity\"><\/span>The <code>.to_owned()<\/code> method generates a <code>Vector<\/code> from a reference array with undefined capacity<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>There is another interesting case of using the <code>.to_owned()<\/code> method results in a duplicate of a different type. This happens when applying <code>.to_owned()<\/code> to reference arrays with undefined capacity, such as,<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>&amp;[i8]<\/code> <\/li><li><code>&amp;[i16]<\/code><\/li><li><code>&amp;[i32]<\/code><\/li><li><code>&amp;[i64]<\/code><\/li><li><code>&amp;[i128]<\/code><\/li><li><code>&amp;[u8]<\/code> <\/li><li><code>&amp;[u16]<\/code><\/li><li><code>&amp;[u32]<\/code><\/li><li><code>&amp;[u64]<\/code><\/li><li><code>&amp;[u128]<\/code><\/li><\/ul>\n\n\n\n<p>generates a vector<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>Vec&lt;i8&gt;<\/code><\/li><li><code>Vec&lt;i16&gt;<\/code><\/li><li><code>Vec&lt;i32&gt;<\/code><\/li><li><code>Vec&lt;i64&gt;<\/code><\/li><li><code>Vec&lt;i128&gt;<\/code><\/li><li><code>Vec&lt;u8&gt;<\/code><\/li><li><code>Vec&lt;u16&gt;<\/code><\/li><li><code>Vec&lt;u32&gt;<\/code><\/li><li><code>Vec&lt;u64&gt;<\/code><\/li><li><code>Vec&lt;u128&gt;<\/code><\/li><\/ul>\n\n\n\n<p>respectively.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let array_i8: &amp;&#91;i8] = &amp;&#91;1, 2, 3];\nlet cloned_array_i8 = array_i8.to_owned(); \/\/ type is Vec&lt;i8&gt;\n\nlet array_i16: &amp;&#91;i16] = &amp;&#91;1, 2, 3];\nlet cloned_array_i16 = array_i16.to_owned(); \/\/ type is Vec&lt;i16&gt;\n\nlet array_i32: &amp;&#91;i32] = &amp;&#91;1, 2, 3];\nlet cloned_array_i32 = array_i32.to_owned(); \/\/ type is Vec&lt;i32&gt;\n\nlet array_i64: &amp;&#91;i64] = &amp;&#91;1, 2, 3];\nlet cloned_array_i64 = array_i64.to_owned(); \/\/ type is Vec&lt;i64&gt;\n\nlet array_i128: &amp;&#91;i128] = &amp;&#91;1, 2, 3];\nlet cloned_array_i128 = array_i128.to_owned(); \/\/ type is Vec&lt;i128&gt;\n\nlet array_u8: &amp;&#91;u8] = &amp;&#91;1, 2, 3];\nlet cloned_array_u8 = array_u8.to_owned(); \/\/ type is Vec&lt;u8&gt;\n\nlet array_u16: &amp;&#91;u16] = &amp;&#91;1, 2, 3];\nlet cloned_array_u16 = array_u16.to_owned(); \/\/ type is Vec&lt;u16&gt;\n\nlet array_u32: &amp;&#91;u32] = &amp;&#91;1, 2, 3];\nlet cloned_array_u32 = array_u32.to_owned(); \/\/ type is Vec&lt;u32&gt;\n\nlet array_u64: &amp;&#91;u64] = &amp;&#91;1, 2, 3];\nlet cloned_array_u64 = array_u64.to_owned(); \/\/ type is Vec&lt;u64&gt;\n\nlet array_u128: &amp;&#91;u128] = &amp;&#91;1, 2, 3];\nlet cloned_array_u128 = array_u128.to_owned(); \/\/ type is Vec&lt;u128&gt;<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In this article, you learned the difference between <code>.clone()<\/code> and <code>.to_owned()<\/code> despite them being similar in their functionality. The key difference to remember is that while <code>.clone()<\/code> attempts to go from borrowed to owned state, that is not always possible as <code>Clone<\/code> works only from <code>&amp;T<\/code> to <code>T<\/code>. <\/p>\n\n\n\n<p>On the other hand, <code>to_owned()<\/code> makes sure the duplicate value has ownership even if that means having to use a different data type such as a <code>String<\/code> or a <code>Vec&lt;u8&gt;<\/code> when  generating a duplicate for  a <code>&amp;str<\/code> or a <code>&amp;[u8]<\/code> .<\/p>\n\n\n\n<p><strong>Was this a tough concept, right?<\/strong><\/p>\n\n\n\n<p>Indeed it is, and it takes a decent amount of time to understand concepts in Rust. Hopefully, this article helped you have more clarity on these two methods (<code>.clone()<\/code> and <code>to_owned()<\/code> ). <\/p>\n\n\n\n<p>Let me know what you thought of this article by replying us in <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noopener\">Twitter of Become a Better Programmer<\/a> or to <a href=\"https:\/\/twitter.com\/arealesramirez\" target=\"_blank\" rel=\"noopener\">my personal account<\/a>. <\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">What&#39;s difference between using the .clone() method and the .to_owned() method in <a href=\"https:\/\/twitter.com\/hashtag\/Rust?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#Rust<\/a>?<br><br>They behave aaaaaaalmost the same. But they aren&#39;t <br><br>In our latest edition of Rust articles, we get an in-depth understanding of these two methods. <a href=\"https:\/\/t.co\/hH8UDH1nYr\">https:\/\/t.co\/hH8UDH1nYr<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1551565598655643649?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">July 25, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Chances are you recently came across the definition of the ToOwned trait to realize it is a generalization of the Clone trait? If so, what is the difference between the two traits? more specifically, what is the difference between .clone() and .to_owned() if they work the same? A generalization of Clone to borrowed data. https:\/\/doc.rust-lang.org\/std\/borrow\/trait.ToOwned.html#tymethod.to_owned &#8230; <a title=\"Rust | The Difference Between .clone() and .to_owned()\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-clone-vs-to_owned\/\" aria-label=\"More on Rust | The Difference Between .clone() and .to_owned()\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":3257,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[31],"tags":[],"class_list":["post-3049","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-rust","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3049","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=3049"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3049\/revisions"}],"predecessor-version":[{"id":3884,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/3049\/revisions\/3884"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/3257"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=3049"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=3049"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=3049"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}