Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

clone
rust
communitycreator

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

okwudili onyejiaku

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);
}
Create a clone in Rust

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.

RELATED TAGS

clone
rust
communitycreator
RELATED COURSES

View all Courses

Keep Exploring