{"id":4051,"date":"2022-09-06T21:44:08","date_gmt":"2022-09-07T02:44:08","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=4051"},"modified":"2022-09-11T08:43:23","modified_gmt":"2022-09-11T13:43:23","slug":"rust-dereference-unary-operator","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-dereference-unary-operator\/","title":{"rendered":"What is the Meaning of the Asterisk * Symbol in Rust?"},"content":{"rendered":"\n<p>Have you recently seen the asterisk (<code>*<\/code>) symbol in Rust while reading someone else&#8217;s code and you are not sure what it means? No worries, this article will explain the meaning of <code>*<\/code> and show you how it can become handy during development.<\/p>\n\n\n\n<p><strong>The asterisk (<code>*<\/code>) symbol is Rust&#8217;s dereference unary operator. The dereference operator extracts the value of a variable omitting the pointer or reference.<\/strong> <strong>To use the dereference operator, add the asterisk (<code>*<\/code>) symbol right before a given variable <code>T<\/code><\/strong>.<strong> This will result in <code>*T<\/code> which gets the value of <code>T<\/code>.<\/strong> <\/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-dereference-unary-operator\/#Understanding_the_Dereference_Operator\" >Understanding the Dereference Operator<\/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-dereference-unary-operator\/#Understanding_pointers\" >Understanding pointers<\/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-dereference-unary-operator\/#Dereferencing_values_from_pointers\" >Dereferencing values from pointers<\/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-dereference-unary-operator\/#Derefencing_a_mutable_references\" >Derefencing a mutable references<\/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-dereference-unary-operator\/#Derefencing_a_smart_pointers\" >Derefencing a smart pointers<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-dereference-unary-operator\/#Dereferencing_Strings\" >Dereferencing Strings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-dereference-unary-operator\/#Derefererencing_Structs\" >Derefererencing Structs<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-dereference-unary-operator\/#Derefencing_raw_pointers\" >Derefencing raw pointers<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-dereference-unary-operator\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_the_Dereference_Operator\"><\/span>Understanding the Dereference Operator<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Take a look at the following example to get a better understanding of the dereference operator.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n  let my_number = 1;\n  let other_number = *&amp;my_number;\n\n  assert_eq!(my_number, other_number);\n}<\/code><\/pre>\n\n\n\n<p>The previous code assigns the value to <code>other_number<\/code> by dereferencing the shared reference of <code>my_number<\/code> (<code>&amp;my_number<\/code>). Finally, the code asserts that the values of <code>my_number<\/code> and <code>other_number<\/code> are equal. <\/p>\n\n\n\n<p>This is the same as duplicating the value of <code>my_number<\/code> to <code>other_number<\/code> <a href=\"https:\/\/www.becomebetterprogrammer.com\/rust-copy-vs-clone-trait\/\">by implicitly generating a copy.<\/a><\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n  let my_number = 1;\n  let other_number = my_number;\n\n  assert_eq!(my_number, other_number);\n}<\/code><\/pre>\n\n\n\n<p>If both code snippets are the same, then, is the purpose of the dereference operator to generate a duplicate value?<\/p>\n\n\n\n<p><em>Kind of.<\/em><\/p>\n\n\n\n<p>An important aspect is that the dereference operator is used in pointer types.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_pointers\"><\/span>Understanding pointers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>A pointer is another way to tell what the memory address variables have. An example of an address in memory could be <code>0x80537ff7fc<\/code> or <code>0x80537ff814<\/code>.<\/p>\n\n\n\n<p>If you want to see the pointer or memory location of a variable use the format <code>{:p}<\/code>  when using the <code>println!<\/code> macro. This will display the memory location as a hexadecimal number.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n   let my_number = 1;\n   println!(\"my_number memory location {:p}\", &amp;my_number);\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Dereferencing_values_from_pointers\"><\/span>Dereferencing values from pointers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Rust has different pointer types. These are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Shared References (&amp;)<\/li><li>Mutable References (&amp;mut)<\/li><li>Raw pointers (*const and *mut)<\/li><li><a href=\"https:\/\/doc.rust-lang.org\/book\/ch15-00-smart-pointers.html\" target=\"_blank\" rel=\"noopener\">Smart Pointers<\/a><\/li><\/ul>\n\n\n\n<p>If I bring back the initial code snippet used to show the behavior of the dereference operator,<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n  let my_number = 1;\n  let other_number = *&amp;my_number;\n\n  assert_eq!(my_number, other_number);\n}<\/code><\/pre>\n\n\n\n<p>you will notice the unary (<code>*<\/code>) operator is used on a shared reference <code>&amp;my_number<\/code> rather than directly on <code>my_number<\/code>. If you attempt to user the unary operator in <code>my_number<\/code> , .i.e., <code>*my_number<\/code>, you will get the following error:<\/p>\n\n\n\n<p><code>error[E0614]: type {integer} cannot be dereferenced<\/code><\/p>\n\n\n\n<p>This is because the <code>i32<\/code> type doesn&#8217;t implement the <a href=\"https:\/\/doc.rust-lang.org\/std\/ops\/trait.Deref.html\" target=\"_blank\" rel=\"noopener\"><code>Deref<\/code> trait<\/a>.<\/p>\n\n\n\n<p><strong>To use the dereference operator, the type that the dereference operator is applied to needs to implement the <code>Deref<\/code> trait and <a href=\"https:\/\/doc.rust-lang.org\/std\/ops\/trait.DerefMut.html\" target=\"_blank\" rel=\"noopener\"><code>DerefMut<\/code> trait<\/a> for mutable references.<\/strong><\/p>\n\n\n\n<p>Since you cannot use the unary (<code>*<\/code> ) operator on <code>my_number<\/code>, you will need to get a shared reference (<code>&amp;<\/code>) of the variable, meaning <code>&amp;my_number<\/code> to use the dereference operator. <\/p>\n\n\n\n<p>In other words, <code>&amp;my_number<\/code> will get an address in memory which serves only as a reference of the location of value <code>1<\/code>. <\/p>\n\n\n\n<p>Now, since the address of <code>&amp;my_number<\/code> could be something like <code>0x6e047ffa14<\/code> , to extract the value that is referencing the address <code>0x6e047ffa14<\/code>, you will use the dereference unary operator <code>*&amp;my_number<\/code>, which results in the value of <code>1<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Derefencing_a_mutable_references\"><\/span>Derefencing a mutable references<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The derefence operator can become handy when updating the value of mutable references. Given the following example, <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn dereferencing_mutable_references() {\n    let text = &amp;mut String::from(\"foo\");\n    *text = String::from(\"bar\");\n\n    assert_eq!(text, \"bar\");\n}<\/code><\/pre>\n\n\n\n<p>notice how the unary (<code>*<\/code>) operator in here is used to assign a new value <code>String::from(\"bar\")<\/code>  with a type of <code>&amp;mut String<\/code>. This allows you to reassign the value over an over.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn dereferencing_mutable_references() {\n    let text = &amp;mut String::from(\"foo\");\n    *text = String::from(\"one\");\n    *text = String::from(\"two\");\n    *text = String::from(\"three\");\n    *text = String::from(\"four\");\n    *text = String::from(\"five\");\n}<\/code><\/pre>\n\n\n\n<p>If you attempt to reassign the value of <code>text<\/code> without using the unary (<code>*<\/code>) operator, like you see in the following example,<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let text = &amp;mut String::from(\"foo\");\n    text = String::from(\"one\");\n}<\/code><\/pre>\n\n\n\n<p>you will get the following error <code>error[E0384]: cannot assign twice to immutable variable text<\/code> .<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Derefencing_a_smart_pointers\"><\/span>Derefencing a smart pointers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Dereferencing_Strings\"><\/span>Dereferencing Strings<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Here is an example of dereferencing a String, which is a smart pointer.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>\/\/ Strings are considered smart pointers as they own memory and allow you to manipulate\n\/\/ it as well as having other metadata such as \"capacity\"\nfn dereferencing_strings() {\n    let string = String::from(\"Hello\");\n    \/\/ *string will generate a string literal str without a known size at compilation time\n    \/\/ Hence, if you attempt,\n    \/\/ let other_string = *string;\n    \/\/ the code have errors at compilation time.\n\n    let other_str = &amp;*string;\n    let other_string = String::from(&amp;*string);\n\n    assert_eq!(string, other_str);\n    assert_eq!(string, other_string);\n}<\/code><\/pre>\n\n\n\n<p>If you paid closed attention to the code, you will find out that <code>*String::from(\"Hello\")<\/code> or <code>*my_string<\/code> can&#8217;t be used without getting a shared reference <code>&amp;<\/code> of the value. The reason for this is, <code>*my_string<\/code> will generate a <a href=\"https:\/\/www.becomebetterprogrammer.com\/rust-string-vs-str\/\">string literal (<code>str<\/code> )<\/a>. Unfortunately, it is not possible for a variable to own a string literal. That&#8217;s why it is necessary to get the shared reference of <code>*my_string<\/code> or  <code>&amp;*string;<\/code><\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Derefererencing_Structs\"><\/span>Derefererencing Structs<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Structs are also smart pointers. Custom structs can&#8217;t use the dereference operator as they don&#8217;t implement the Deref trait by default as you can see in the following snippet of code,<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>#&#91;derive(Debug)]\nstruct MyStruct {\n    value: i32,\n    another_value: i32\n}\n\nfn dereferencing_structs() {\n    let my_struct = MyStruct {value: 1, another_value: 2};\n    \/\/ this code will fail in here\n    let value = *my_struct;\n\n    assert_eq!(1, value);\n}<\/code><\/pre>\n\n\n\n<p>In this case, it is not possible to know which value from the struct <code>MyStruct<\/code> Rust will attempt to dereference as <code>MyStruct<\/code> has the keys <code>value<\/code> and <code>another_value<\/code>.<\/p>\n\n\n\n<p>To allow dereferencing on the struct <code>MyStruct<\/code>, implement the <code>Deref<\/code> trait.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>use std::ops::Deref;\n\n#&#91;derive(Debug)]\nstruct MyStruct {\n    value: i32,\n    another_value: String\n}\n\nimpl Deref for MyStruct {\n    type Target = i32;\n\n    fn deref(&amp;self) -&gt; &amp;Self::Target {\n        &amp;self.value\n    }\n}\n\nfn dereferencing_structs() {\n    let my_struct = MyStruct {value: 1, another_value: String::from(\"a\")};\n    let test = *my_struct;\n\n    assert_eq!(1, test);\n}<\/code><\/pre>\n\n\n\n<p>When implementing <code>Deref<\/code> , it is required to define the type <code>Target<\/code>. This <code>Target<\/code> type should match the dereferenced value of any of the struct <code>MyStruct<\/code> keys (<code>value<\/code>, <code>another_value<\/code>).  For this example, the type <code>Target<\/code> is based on <code>value<\/code> (<code>i32<\/code>).<\/p>\n\n\n\n<p>Then, to finalize implementing the <code>Deref<\/code> trait, add the <code>deref<\/code> function. This function returns the key <code>value<\/code> of the struct <code>MyStruct<\/code>. Therefore, once you use the dereference operator on an instance of <code>MyStruct<\/code>, it will extract the data from the <code>value<\/code> key.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>let my_struct = MyStruct {value: 1, another_value: String::from(\"a\")};\nlet test = *my_struct;\n\nassert_eq!(1, test);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Derefencing_raw_pointers\"><\/span>Derefencing raw pointers<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The types <code>*const T<\/code>  and <code>*mut T<\/code> are considered raw pointers. <a href=\"https:\/\/doc.rust-lang.org\/reference\/unsafety.html\" data-type=\"URL\" data-id=\"https:\/\/doc.rust-lang.org\/reference\/unsafety.html\" target=\"_blank\" rel=\"noopener\">According to the rust documentation<\/a>, dereferencing a raw pointer is an unsafe operation. Hence, if you attempt to dereference a raw pointer, such as, <\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn dereferencing_raw_pointers() {\n    let test = \"Hello!\";\n    let raw = &amp;test as *const &amp;str;\n    \n    \/\/ This will fail with the error error&#91;E0614]: type `i32` cannot be dereferenced\n    let another_test =  *raw ;\n}<\/code><\/pre>\n\n\n\n<p>Rust will throw the following error at compile time: <\/p>\n\n\n\n<p><code>error[E0614]: type i32 cannot be dereferenced<\/code><\/p>\n\n\n\n<p>However, Rust allows to dereference raw pointers as long as you use the <code>unsafe<\/code> keyword.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn dereferencing_raw_pointers() {\n    let test = \"Hello!\";\n    let raw = &amp;test as *const &amp;str;\n    let another_test = unsafe { *raw };\n\n    assert_eq!(\"Hello!\", another_test);\n}<\/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>All in all, this article explain the meaning of the asterisk (<code>*<\/code>) symbol in Rust, which is the dereference unary operator. The dereference operator is in charge of extracting the value off of a pointer or reference. A pointer is a memory location assigned to a variable in Rust. It is possible to use the dereference operator in all the different pointer types:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Shared References (&amp;)<\/li><li>Mutable References (&amp;mut)<\/li><li>Raw pointers (*const and *mut)<\/li><li>Smart Pointers<\/li><\/ul>\n\n\n\n<p>For those Rust types that you cannot use the dereference operator, implement the <code>Deref<\/code> and\/or <code>DerefMut<\/code> traits.<\/p>\n\n\n\n<p>If you want to checkout all the examples used in this article, feel free to find them in my repository <a href=\"https:\/\/github.com\/arealesramirez\/rust-deference-operator-examples\" target=\"_blank\" rel=\"noopener\">https:\/\/github.com\/arealesramirez\/rust-deference-operator-examples<\/a>.<\/p>\n\n\n\n<p><strong>Do you understand what the asterisks symbol means now?<\/strong><\/p>\n\n\n\n<p>Share your thoughts, comments, suggestions in the <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 Twitter 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\">Do you know what the asterisk (*) sign is used in <a href=\"https:\/\/twitter.com\/rustlang?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">@rustlang<\/a> ?<br><br>It is the dereference unary operator and it helps you get the data from any pointer as long as its type implements the Deref or DerefMut traits.<br><br>Here&#39;s an article to get understand better!<a href=\"https:\/\/t.co\/gVKUXiFQDq\">https:\/\/t.co\/gVKUXiFQDq<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1567343997797949441?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">September 7, 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>Have you recently seen the asterisk (*) symbol in Rust while reading someone else&#8217;s code and you are not sure what it means? No worries, this article will explain the meaning of * and show you how it can become handy during development. The asterisk (*) symbol is Rust&#8217;s dereference unary operator. The dereference operator &#8230; <a title=\"What is the Meaning of the Asterisk * Symbol in Rust?\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-dereference-unary-operator\/\" aria-label=\"More on What is the Meaning of the Asterisk * Symbol in Rust?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":4062,"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-4051","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\/4051","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=4051"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4051\/revisions"}],"predecessor-version":[{"id":4174,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4051\/revisions\/4174"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/4062"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=4051"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=4051"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=4051"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}