Generic swap: Difference between revisions

m
Whitespace for clarity, moved the task relevant function to it's own code block, and put the less interesting main function used to showcase its use in its own block at the end
(Moved the generic swap code into its own function in accordance with the task description. Added short description.)
m (Whitespace for clarity, moved the task relevant function to it's own code block, and put the less interesting main function used to showcase its use in its own block at the end)
Line 2,691:
 
=={{header|Rust}}==
Rust does not allow for swapping the value of two variables with different types, but if the types are the same it can be done using generic types and lifetimes. Type hints have been added for clarity.
<lang rust>
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
std::mem::swap(var1, var2)
</lang>
With a main function of
<lang rust>
fn main() {
Line 2,698 ⟶ 2,704:
let mut c: i32 = 1;
let mut d: i32 = 2;
 
generic_swap(&mut a, &mut b);
generic_swap(&mut c, &mut d);
 
println!("a={}, b={}", a, b);
println!("c={}, d={}", c, d);
}
 
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {
std::mem::swap(var1, var2)
 
</lang>
we get the output:
 
{{out}}
<pre>
19

edits