@@ -1982,6 +1982,51 @@ impl Add<&str> for String {
1982
1982
}
1983
1983
}
1984
1984
1985
+ /// Implements the `+` operator for concatenating a string and a char together.
1986
+ ///
1987
+ /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if
1988
+ /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on
1989
+ /// every operation, which would lead to `O(n^2)` running time when building an `n`-byte string by
1990
+ /// repeated concatenation.
1991
+ ///
1992
+ /// # Examples
1993
+ ///
1994
+ /// Concatenating a `String` with a `char` takes the `String` by value and copies the `char`:
1995
+ ///
1996
+ /// ```
1997
+ /// let a = String::from("hello world! ");
1998
+ /// let b = char::from('👋');
1999
+ /// let c = a + b;
2000
+ /// // `a` is moved and can no longer be used here.
2001
+ /// ```
2002
+ ///
2003
+ /// If you want to keep using the initial `String`, you can clone it and append to the clone instead:
2004
+ ///
2005
+ /// ```
2006
+ /// let a = String::from("hello world! ");
2007
+ /// let b = char::from('👋');
2008
+ /// let c = a.clone() + b;
2009
+ /// // `a` is still valid here.
2010
+ /// ```
2011
+ ///
2012
+ /// Concatenating `char` to a `&str` slice can be done by converting the `&str` to a `String`:
2013
+ ///
2014
+ /// ```
2015
+ /// let a = "hello world! ";
2016
+ /// let b = '👋';
2017
+ /// let c = a.to_string() + b;
2018
+ /// ```
2019
+ #[ stable( feature = "add_string_and_char" , since = "1.41.0" ) ]
2020
+ impl Add < char > for String {
2021
+ type Output = String ;
2022
+
2023
+ #[ inline]
2024
+ fn add ( mut self , other : char ) -> String {
2025
+ self . push ( other) ;
2026
+ self
2027
+ }
2028
+ }
2029
+
1985
2030
/// Implements the `+=` operator for appending to a `String`.
1986
2031
///
1987
2032
/// This has the same behavior as the [`push_str`][String::push_str] method.
@@ -1993,6 +2038,17 @@ impl AddAssign<&str> for String {
1993
2038
}
1994
2039
}
1995
2040
2041
+ /// Implements the `+=` operator for appending a `char` to a `String`.
2042
+ ///
2043
+ /// This has the same behavior as the [`push`][String::push] method.
2044
+ #[ stable( feature = "stringaddassign_char" , since = "1.41.0" ) ]
2045
+ impl AddAssign < char > for String {
2046
+ #[ inline]
2047
+ fn add_assign ( & mut self , other : char ) {
2048
+ self . push ( other) ;
2049
+ }
2050
+ }
2051
+
1996
2052
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1997
2053
impl ops:: Index < ops:: Range < usize > > for String {
1998
2054
type Output = str ;
0 commit comments