1.0.0[−][src]Struct std::string::String
A UTF-8 encoded, growable string.
The String
type is the most common string type that has ownership over the
contents of the string. It has a close relationship with its borrowed
counterpart, the primitive str
.
Examples
You can create a String
from a literal string with String::from
:
let hello = String::from("Hello, world!");Run
You can append a char
to a String
with the push
method, and
append a &str
with the push_str
method:
let mut hello = String::from("Hello, "); hello.push('w'); hello.push_str("orld!");Run
If you have a vector of UTF-8 bytes, you can create a String
from it with
the from_utf8
method:
// some bytes, in a vector let sparkle_heart = vec![240, 159, 146, 150]; // We know these bytes are valid, so we'll use `unwrap()`. let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); assert_eq!("💖", sparkle_heart);Run
UTF-8
String
s are always valid UTF-8. This has a few implications, the first of
which is that if you need a non-UTF-8 string, consider OsString
. It is
similar, but without the UTF-8 constraint. The second implication is that
you cannot index into a String
:
let s = "hello"; println!("The first letter of s is {}", s[0]); // ERROR!!!Run
Indexing is intended to be a constant-time operation, but UTF-8 encoding
does not allow us to do this. Furthermore, it's not clear what sort of
thing the index should return: a byte, a codepoint, or a grapheme cluster.
The bytes
and chars
methods return iterators over the first
two, respectively.
Deref
String
s implement Deref
<Target=str>
, and so inherit all of str
's
methods. In addition, this means that you can pass a String
to a
function which takes a &str
by using an ampersand (&
):
fn takes_str(s: &str) { } let s = String::from("Hello"); takes_str(&s);Run
This will create a &str
from the String
and pass it in. This
conversion is very inexpensive, and so generally, functions will accept
&str
s as arguments unless they need a String
for some specific
reason.
In certain cases Rust doesn't have enough information to make this
conversion, known as Deref
coercion. In the following example a string
slice &'a str
implements the trait TraitExample
, and the function
example_func
takes anything that implements the trait. In this case Rust
would need to make two implicit conversions, which Rust doesn't have the
means to do. For that reason, the following example will not compile.
trait TraitExample {} impl<'a> TraitExample for &'a str {} fn example_func<A: TraitExample>(example_arg: A) {} fn main() { let example_string = String::from("example_string"); example_func(&example_string); }Run
There are two options that would work instead. The first would be to
change the line example_func(&example_string);
to
example_func(example_string.as_str());
, using the method as_str()
to explicitly extract the string slice containing the string. The second
way changes example_func(&example_string);
to
example_func(&*example_string);
. In this case we are dereferencing a
String
to a str
, then referencing the str
back to
&str
. The second way is more idiomatic, however both work to do the
conversion explicitly rather than relying on the implicit conversion.
Representation
A String
is made up of three components: a pointer to some bytes, a
length, and a capacity. The pointer points to an internal buffer String
uses to store its data. The length is the number of bytes currently stored
in the buffer, and the capacity is the size of the buffer in bytes. As such,
the length will always be less than or equal to the capacity.
This buffer is always stored on the heap.
You can look at these with the as_ptr
, len
, and capacity
methods:
use std::mem; let story = String::from("Once upon a time..."); let ptr = story.as_ptr(); let len = story.len(); let capacity = story.capacity(); // story has nineteen bytes assert_eq!(19, len); // Now that we have our parts, we throw the story away. mem::forget(story); // We can re-build a String out of ptr, len, and capacity. This is all // unsafe because we are responsible for making sure the components are // valid: let s = unsafe { String::from_raw_parts(ptr as *mut _, len, capacity) } ; assert_eq!(String::from("Once upon a time..."), s);Run
If a String
has enough capacity, adding elements to it will not
re-allocate. For example, consider this program:
let mut s = String::new(); println!("{}", s.capacity()); for _ in 0..5 { s.push_str("hello"); println!("{}", s.capacity()); }Run
This will output the following:
0
5
10
20
20
40
At first, we have no memory allocated at all, but as we append to the
string, it increases its capacity appropriately. If we instead use the
with_capacity
method to allocate the correct capacity initially:
let mut s = String::with_capacity(25); println!("{}", s.capacity()); for _ in 0..5 { s.push_str("hello"); println!("{}", s.capacity()); }Run
We end up with a different output:
25
25
25
25
25
25
Here, there's no need to allocate more memory inside the loop.
Methods
impl String
[src][−]
pub fn new() -> String
[src][+]
pub fn with_capacity(capacity: usize) -> String
[src][+]
pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>
[src][+]
pub fn from_utf8_lossy(v: &'a [u8]) -> Cow<'a, str>
[src][+]
pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>
[src][+]
pub fn from_utf16_lossy(v: &[u16]) -> String
[src][+]
pub unsafe fn from_raw_parts(
buf: *mut u8,
length: usize,
capacity: usize
) -> String
[src][+]
buf: *mut u8,
length: usize,
capacity: usize
) -> String
pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String
[src][+]
pub fn into_bytes(self) -> Vec<u8>
[src][+]
pub fn as_str(&self) -> &str
1.7.0[src][+]
pub fn as_mut_str(&mut self) -> &mut str
1.7.0[src][+]
pub fn push_str(&mut self, string: &str)
[src][+]
pub fn capacity(&self) -> usize
[src][+]
pub fn reserve(&mut self, additional: usize)
[src][+]
pub fn reserve_exact(&mut self, additional: usize)
[src][+]
pub fn try_reserve(
&mut self,
additional: usize
) -> Result<(), CollectionAllocErr>
[src][+]
&mut self,
additional: usize
) -> Result<(), CollectionAllocErr>
🔬 This is a nightly-only experimental API. (try_reserve
#48043)
new API
pub fn try_reserve_exact(
&mut self,
additional: usize
) -> Result<(), CollectionAllocErr>
[src][+]
&mut self,
additional: usize
) -> Result<(), CollectionAllocErr>
🔬 This is a nightly-only experimental API. (try_reserve
#48043)
new API
pub fn shrink_to_fit(&mut self)
[src][+]
pub fn shrink_to(&mut self, min_capacity: usize)
[src][+]
🔬 This is a nightly-only experimental API. (shrink_to
#56431)
new API
pub fn push(&mut self, ch: char)
[src][+]
pub fn as_bytes(&self) -> &[u8]
[src][+]
pub fn truncate(&mut self, new_len: usize)
[src][+]
pub fn pop(&mut self) -> Option<char>
[src][+]
pub fn remove(&mut self, idx: usize) -> char
[src][+]
pub fn retain<F>(&mut self, f: F) where
F: FnMut(char) -> bool,
1.26.0[src][+]
F: FnMut(char) -> bool,
pub fn insert(&mut self, idx: usize, ch: char)
[src][+]
pub fn insert_str(&mut self, idx: usize, string: &str)
1.16.0[src][+]
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8>
[src][+]
pub fn len(&self) -> usize
[src][+]
pub fn is_empty(&self) -> bool
[src][+]
pub fn split_off(&mut self, at: usize) -> String
1.16.0[src][+]
pub fn clear(&mut self)
[src][+]
ⓘImportant traits for Drain<'_>pub fn drain<R>(&mut self, range: R) -> Drain where
R: RangeBounds<usize>,
1.6.0[src][+]
R: RangeBounds<usize>,
pub fn replace_range<R>(&mut self, range: R, replace_with: &str) where
R: RangeBounds<usize>,
1.27.0[src][+]
R: RangeBounds<usize>,
ⓘImportant traits for Box<I>pub fn into_boxed_str(self) -> Box<str>
1.4.0[src][+]
Methods from Deref<Target = str>
pub fn len(&self) -> usize
[src][+]
pub fn is_empty(&self) -> bool
[src][+]
pub fn is_char_boundary(&self, index: usize) -> bool
1.9.0[src][+]
pub fn as_bytes(&self) -> &[u8]
[src][+]
pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8]
1.20.0[src][+]
pub const fn as_ptr(&self) -> *const u8
[src][+]
pub fn as_mut_ptr(&mut self) -> *mut u8
[src][+]
pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output> where
I: SliceIndex<str>,
1.20.0[src][+]
I: SliceIndex<str>,
pub fn get_mut<I>(
&mut self,
i: I
) -> Option<&mut <I as SliceIndex<str>>::Output> where
I: SliceIndex<str>,
1.20.0[src][+]
&mut self,
i: I
) -> Option<&mut <I as SliceIndex<str>>::Output> where
I: SliceIndex<str>,
pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Output where
I: SliceIndex<str>,
1.20.0[src][+]
I: SliceIndex<str>,
pub unsafe fn get_unchecked_mut<I>(
&mut self,
i: I
) -> &mut <I as SliceIndex<str>>::Output where
I: SliceIndex<str>,
1.20.0[src][+]
&mut self,
i: I
) -> &mut <I as SliceIndex<str>>::Output where
I: SliceIndex<str>,
pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str
[src][+]
use get_unchecked(begin..end)
instead
pub unsafe fn slice_mut_unchecked(
&mut self,
begin: usize,
end: usize
) -> &mut str
1.5.0[src][+]
&mut self,
begin: usize,
end: usize
) -> &mut str
use get_unchecked_mut(begin..end)
instead
pub fn split_at(&self, mid: usize) -> (&str, &str)
1.4.0[src][+]
pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)
1.4.0[src][+]
ⓘImportant traits for Chars<'a>pub fn chars(&self) -> Chars
[src][+]
ⓘImportant traits for CharIndices<'a>pub fn char_indices(&self) -> CharIndices
[src][+]
ⓘImportant traits for Bytes<'_>pub fn bytes(&self) -> Bytes
[src][+]
ⓘImportant traits for SplitWhitespace<'a>pub fn split_whitespace(&self) -> SplitWhitespace
1.1.0[src][+]
ⓘImportant traits for SplitAsciiWhitespace<'a>pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace
1.34.0[src][+]
ⓘImportant traits for Lines<'a>pub fn lines(&self) -> Lines
[src][+]
ⓘImportant traits for LinesAny<'a>pub fn lines_any(&self) -> LinesAny
[src][+]
use lines() instead now
ⓘImportant traits for EncodeUtf16<'a>pub fn encode_utf16(&self) -> EncodeUtf16
1.8.0[src][+]
pub fn contains<'a, P>(&'a self, pat: P) -> bool where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
pub fn starts_with<'a, P>(&'a self, pat: P) -> bool where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
pub fn ends_with<'a, P>(&'a self, pat: P) -> bool where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn find<'a, P>(&'a self, pat: P) -> Option<usize> where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
pub fn rfind<'a, P>(&'a self, pat: P) -> Option<usize> where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
ⓘImportant traits for Split<'a, P>pub fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
ⓘImportant traits for RSplit<'a, P>pub fn rsplit<'a, P>(&'a self, pat: P) -> RSplit<'a, P> where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
ⓘImportant traits for SplitTerminator<'a, P>pub fn split_terminator<'a, P>(&'a self, pat: P) -> SplitTerminator<'a, P> where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
ⓘImportant traits for RSplitTerminator<'a, P>pub fn rsplit_terminator<'a, P>(&'a self, pat: P) -> RSplitTerminator<'a, P> where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
ⓘImportant traits for SplitN<'a, P>pub fn splitn<'a, P>(&'a self, n: usize, pat: P) -> SplitN<'a, P> where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
ⓘImportant traits for RSplitN<'a, P>pub fn rsplitn<'a, P>(&'a self, n: usize, pat: P) -> RSplitN<'a, P> where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
ⓘImportant traits for Matches<'a, P>pub fn matches<'a, P>(&'a self, pat: P) -> Matches<'a, P> where
P: Pattern<'a>,
1.2.0[src][+]
P: Pattern<'a>,
ⓘImportant traits for RMatches<'a, P>pub fn rmatches<'a, P>(&'a self, pat: P) -> RMatches<'a, P> where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
1.2.0[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
ⓘImportant traits for MatchIndices<'a, P>pub fn match_indices<'a, P>(&'a self, pat: P) -> MatchIndices<'a, P> where
P: Pattern<'a>,
1.5.0[src][+]
P: Pattern<'a>,
ⓘImportant traits for RMatchIndices<'a, P>pub fn rmatch_indices<'a, P>(&'a self, pat: P) -> RMatchIndices<'a, P> where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
1.5.0[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn trim(&self) -> &str
[src][+]
pub fn trim_start(&self) -> &str
1.30.0[src][+]
pub fn trim_end(&self) -> &str
1.30.0[src][+]
pub fn trim_left(&self) -> &str
[src][+]
superseded by trim_start
pub fn trim_right(&self) -> &str
[src][+]
superseded by trim_end
pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,
pub fn trim_start_matches<'a, P>(&'a self, pat: P) -> &'a str where
P: Pattern<'a>,
1.30.0[src][+]
P: Pattern<'a>,
pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
1.30.0[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
pub fn trim_left_matches<'a, P>(&'a self, pat: P) -> &'a str where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
superseded by trim_start_matches
pub fn trim_right_matches<'a, P>(&'a self, pat: P) -> &'a str where
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
[src][+]
P: Pattern<'a>,
<P as Pattern<'a>>::Searcher: ReverseSearcher<'a>,
superseded by trim_end_matches
pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err> where
F: FromStr,
[src][+]
F: FromStr,
pub fn is_ascii(&self) -> bool
1.23.0[src][+]
pub fn eq_ignore_ascii_case(&self, other: &str) -> bool
1.23.0[src][+]
pub fn make_ascii_uppercase(&mut self)
1.23.0[src][+]
pub fn make_ascii_lowercase(&mut self)
1.23.0[src][+]
ⓘImportant traits for EscapeDebug<'a>pub fn escape_debug(&self) -> EscapeDebug
1.34.0[src][+]
ⓘImportant traits for EscapeDefault<'a>pub fn escape_default(&self) -> EscapeDefault
1.34.0[src][+]
ⓘImportant traits for EscapeUnicode<'a>pub fn escape_unicode(&self) -> EscapeUnicode
1.34.0[src][+]
pub fn replace<'a, P>(&'a self, from: P, to: &str) -> String where
P: Pattern<'a>,
[src][+]
P: Pattern<'a>,
pub fn replacen<'a, P>(&'a self, pat: P, to: &str, count: usize) -> String where
P: Pattern<'a>,
1.16.0[src][+]
P: Pattern<'a>,
pub fn to_lowercase(&self) -> String
1.2.0[src][+]
pub fn to_uppercase(&self) -> String
1.2.0[src][+]
pub fn repeat(&self, n: usize) -> String
1.16.0[src][+]
pub fn to_ascii_uppercase(&self) -> String
1.23.0[src][+]
pub fn to_ascii_lowercase(&self) -> String
1.23.0[src][+]
Trait Implementations
impl<'_> Add<&'_ str> for String
[src][+]
impl Hash for String
[src][+]
impl Debug for String
[src][+]
impl Display for String
[src][+]
impl PartialOrd<String> for String
[src][+]
impl<'a> FromIterator<&'a str> for String
[src][+]
impl FromIterator<String> for String
1.4.0[src][+]
impl<'a> FromIterator<String> for Cow<'a, str>
1.12.0[src][+]
impl FromIterator<char> for String
[src][+]
impl<'a> FromIterator<Cow<'a, str>> for String
1.19.0[src][+]
impl<'a> FromIterator<&'a char> for String
1.17.0[src][+]
impl ToString for String
1.17.0[src][+]
impl<'a, 'b> PartialEq<Cow<'a, str>> for String
[src][+]
impl<'a, 'b> PartialEq<String> for Cow<'a, str>
[src][+]
impl<'a, 'b> PartialEq<String> for str
[src][+]
impl PartialEq<String> for String
[src][+]
impl<'a, 'b> PartialEq<&'a str> for String
[src][+]
impl<'a, 'b> PartialEq<String> for &'a str
[src][+]
impl<'a, 'b> PartialEq<str> for String
[src][+]
impl<'a, 'b> Pattern<'a> for &'b String
[src][+]
type Searcher = <&'b str as Pattern<'a>>::Searcher
fn into_searcher(self, haystack: &'a str) -> <&'b str as Pattern<'a>>::Searcher
[src][+]
fn is_contained_in(self, haystack: &'a str) -> bool
[src][+]
fn is_prefix_of(self, haystack: &'a str) -> bool
[src][+]
fn is_suffix_of(self, haystack: &'a str) -> bool where
Self::Searcher: ReverseSearcher<'a>,
[src][+]
Self::Searcher: ReverseSearcher<'a>,
impl Write for String
[src][+]
impl Extend<char> for String
[src][+]
impl Extend<String> for String
1.4.0[src][+]
impl<'a> Extend<Cow<'a, str>> for String
1.19.0[src][+]
impl<'a> Extend<&'a char> for String
1.2.0[src][+]
impl<'a> Extend<&'a str> for String
[src][+]
impl Clone for String
[src][+]
impl<'_> AddAssign<&'_ str> for String
1.12.0[src][+]
fn add_assign(&mut self, other: &str)
[src][+]
impl Default for String
[src][+]
impl Borrow<str> for String
[src][+]
impl From<String> for Rc<str>
1.21.0[src][+]
impl<'a> From<Cow<'a, str>> for String
1.14.0[src][+]
impl From<String> for Box<str>
1.20.0[src][+]
impl From<String> for Arc<str>
1.21.0[src][+]
impl<'a> From<String> for Cow<'a, str>
[src][+]
impl From<String> for Vec<u8>
1.14.0[src][+]
impl<'_> From<&'_ str> for String
[src][+]
impl<'a> From<&'a String> for Cow<'a, str>
1.28.0[src][+]
impl From<Box<str>> for String
1.18.0[src][+]
impl Eq for String
[src]
impl AsRef<str> for String
[src][+]
impl AsRef<[u8]> for String
[src][+]
impl FromStr for String
[src][+]
impl Index<RangeFull> for String
[src][+]
impl Index<RangeFrom<usize>> for String
[src][+]
impl Index<RangeInclusive<usize>> for String
1.26.0[src][+]
impl Index<RangeToInclusive<usize>> for String
1.26.0[src][+]
impl Index<Range<usize>> for String
[src][+]
impl Index<RangeTo<usize>> for String
[src][+]
impl Ord for String
[src][+]
impl IndexMut<RangeToInclusive<usize>> for String
1.26.0[src][+]
impl IndexMut<RangeFull> for String
1.3.0[src][+]
impl IndexMut<RangeFrom<usize>> for String
1.3.0[src][+]
impl IndexMut<RangeInclusive<usize>> for String
1.26.0[src][+]
impl IndexMut<Range<usize>> for String
1.3.0[src][+]
impl IndexMut<RangeTo<usize>> for String
1.3.0[src][+]
impl DerefMut for String
1.3.0[src][+]
impl Deref for String
[src][+]
impl ToSocketAddrs for String
1.16.0[src][+]
impl From<String> for Box<dyn Error + Send + Sync>
[src][+]
impl From<String> for Box<dyn Error>
1.6.0[src][+]
impl From<String> for OsString
[src][+]
impl From<String> for PathBuf
[src][+]
impl AsRef<OsStr> for String
[src][+]
impl AsRef<Path> for String
[src][+]
Auto Trait Implementations
Blanket Implementations
impl<T> From for T
[src][+]
impl<T, U> TryFrom for T where
U: Into<T>,
[src][+]
U: Into<T>,
impl<T, U> TryInto for T where
U: TryFrom<T>,
[src][+]
U: TryFrom<T>,
impl<T, U> Into for T where
U: From<T>,
[src][+]
U: From<T>,
impl<T> Borrow for T where
T: ?Sized,
[src][+]
T: ?Sized,
impl<T> BorrowMut for T where
T: ?Sized,
[src][+]
T: ?Sized,
impl<T> Any for T where
T: 'static + ?Sized,
[src][+]
T: 'static + ?Sized,
impl<T> ToOwned for T where
T: Clone,
[src][+]
T: Clone,
impl<T> ToString for T where
T: Display + ?Sized,
[src][+]
T: Display + ?Sized,