Why is this important?

A very common error in the likes of C# is when you have the following code:

var myList = new List<int>{1,2,3,4,5,6}; 
var dupVar = myList; 
dupVar.Remove(4); // 4 
foreach(var n in myList) 
    Console.WriteLine(n); 

The output we will get from this may not be as you would expect, which is as follows:

It may be expected that, as we have removed the duplicate from dupVar, the myList variable should still have all of the numbers it was set to originally. In this code, what is happening is that dupVar is known as a copy pointer—we have two variables bound to the same pointer on the stack. While it may not seem that big a deal, we have two variable names that are able to change data. This catches a lot of people out and leads to more memory and content bugs than it is worth.

As Rust only allows one pointer per block, we cannot have the likes of this. Once ownership is transferred, the original bound name can no longer be accessed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset