How to clone a value in Rust with the clone() method

Overview

The clone() method is used to create a copy of a value. The value cloned could be any value type such as character, string, number, boolean, etc.

Syntax

value.clone()
Syntax for clone() method in Rust

Parameters

value: This is the value we want to clone.

Return value

The value returned is a copy of the specified value we want to clone.

Example

fn main(){
// create some values
let char1 = 'E';
let string1 = "Welcome to Edpresso";
let no1 = 200;
let bool1 = true;
// create clones
let clone1 = char1.clone();
let clone2 = string1.clone();
let clone3 = no1.clone();
let clone4 = bool1.clone();
// print clone values
println!("{}", clone1);
println!("{}", clone2);
println!("{}", clone3);
println!("{}", clone4);
}

Explanation

In the code above:

  • In lines 3–6: We create some variables and initialize them with some values.
  • In lines 9–12: We clone the values of the variables using clone().
  • In lines 15–18: We print the values of the clones to the console screen.

Free Resources