Trait copy_from_str::CopyFromStrExt
source · pub trait CopyFromStrExt {
// Required method
fn copy_from_str(&mut self, src: &str);
}
Expand description
Extension method for copying a string into another string.
Required Methods§
sourcefn copy_from_str(&mut self, src: &str)
fn copy_from_str(&mut self, src: &str)
Copies all elements from src
into self
, using a memcpy.
The length of src
must be the same as self
.
Panics
This function will panic if the two strings have different lengths.
Examples
Copying two elements from a string into another:
use copy_from_str::CopyFromStrExt;
let src = "abcd";
let mut dst = String::from(" ");
dst.copy_from_str(&src[2..]);
assert_eq!(src, "abcd");
assert_eq!(dst, "cd");
Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use copy_from_str
on a
single string will result in a compile failure:
ⓘ
use copy_from_str::CopyFromStrExt;
let mut string = String::from("abcde");
string[..2].copy_from_str(&string[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
sub-strings from a string:
use copy_from_str::CopyFromStrExt;
let mut string = String::from("abcde");
{
let (left, right) = string.split_at_mut(2);
left.copy_from_str(&right[1..]);
}
assert_eq!(string, "decde");