1
Fork 0

Use implicit capture syntax in format_args

This updates the standard library's documentation to use the new syntax. The
documentation is worthwhile to update as it should be more idiomatic
(particularly for features like this, which are nice for users to get acquainted
with). The general codebase is likely more hassle than benefit to update: it'll
hurt git blame, and generally updates can be done by folks updating the code if
(and when) that makes things more readable with the new format.

A few places in the compiler and library code are updated (mostly just due to
already having been done when this commit was first authored).
This commit is contained in:
T-O-R-U-S 2022-02-12 23:16:17 +04:00 committed by Mark Rousskov
parent ba14a836c7
commit 72a25d05bf
177 changed files with 724 additions and 734 deletions

View file

@ -1087,12 +1087,12 @@ impl HandlerInner {
let warnings = match self.deduplicated_warn_count { let warnings = match self.deduplicated_warn_count {
0 => String::new(), 0 => String::new(),
1 => "1 warning emitted".to_string(), 1 => "1 warning emitted".to_string(),
count => format!("{} warnings emitted", count), count => format!("{count} warnings emitted"),
}; };
let errors = match self.deduplicated_err_count { let errors = match self.deduplicated_err_count {
0 => String::new(), 0 => String::new(),
1 => "aborting due to previous error".to_string(), 1 => "aborting due to previous error".to_string(),
count => format!("aborting due to {} previous errors", count), count => format!("aborting due to {count} previous errors"),
}; };
if self.treat_err_as_bug() { if self.treat_err_as_bug() {
return; return;

View file

@ -3399,7 +3399,7 @@ declare_lint! {
/// // ^^^^^^^^ /// // ^^^^^^^^
/// // This call to try_into matches both Foo:try_into and TryInto::try_into as /// // This call to try_into matches both Foo:try_into and TryInto::try_into as
/// // `TryInto` has been added to the Rust prelude in 2021 edition. /// // `TryInto` has been added to the Rust prelude in 2021 edition.
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
/// ///

View file

@ -281,7 +281,7 @@ pub struct CaptureInfo {
/// let mut t = (0,1); /// let mut t = (0,1);
/// ///
/// let c = || { /// let c = || {
/// println!("{}",t); // L1 /// println!("{t}"); // L1
/// t.1 = 4; // L2 /// t.1 = 4; // L2
/// }; /// };
/// ``` /// ```

View file

@ -458,10 +458,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// let s: String; // hir_id_s /// let s: String; // hir_id_s
/// let mut p: Point; // his_id_p /// let mut p: Point; // his_id_p
/// let c = || { /// let c = || {
/// println!("{}", s); // L1 /// println!("{s}"); // L1
/// p.x += 10; // L2 /// p.x += 10; // L2
/// println!("{}" , p.y) // L3 /// println!("{}" , p.y); // L3
/// println!("{}", p) // L4 /// println!("{p}"); // L4
/// drop(s); // L5 /// drop(s); // L5
/// }; /// };
/// ``` /// ```

View file

@ -397,7 +397,7 @@ pub mod __alloc_error_handler {
// if there is no `#[alloc_error_handler]` // if there is no `#[alloc_error_handler]`
#[rustc_std_internal_symbol] #[rustc_std_internal_symbol]
pub unsafe extern "C-unwind" fn __rdl_oom(size: usize, _align: usize) -> ! { pub unsafe extern "C-unwind" fn __rdl_oom(size: usize, _align: usize) -> ! {
panic!("memory allocation of {} bytes failed", size) panic!("memory allocation of {size} bytes failed")
} }
// if there is an `#[alloc_error_handler]` // if there is an `#[alloc_error_handler]`

View file

@ -161,7 +161,7 @@ where
/// let readonly = [1, 2]; /// let readonly = [1, 2];
/// let borrowed = Items::new((&readonly[..]).into()); /// let borrowed = Items::new((&readonly[..]).into());
/// match borrowed { /// match borrowed {
/// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b), /// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
/// _ => panic!("expect borrowed value"), /// _ => panic!("expect borrowed value"),
/// } /// }
/// ///

View file

@ -31,7 +31,7 @@
//! } //! }
//! //!
//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//! println!("{:?}", list); //! println!("{list:?}");
//! ``` //! ```
//! //!
//! This will print `Cons(1, Cons(2, Nil))`. //! This will print `Cons(1, Cons(2, Nil))`.
@ -1408,7 +1408,7 @@ impl<T: Copy> From<&[T]> for Box<[T]> {
/// let slice: &[u8] = &[104, 101, 108, 108, 111]; /// let slice: &[u8] = &[104, 101, 108, 108, 111];
/// let boxed_slice: Box<[u8]> = Box::from(slice); /// let boxed_slice: Box<[u8]> = Box::from(slice);
/// ///
/// println!("{:?}", boxed_slice); /// println!("{boxed_slice:?}");
/// ``` /// ```
fn from(slice: &[T]) -> Box<[T]> { fn from(slice: &[T]) -> Box<[T]> {
let len = slice.len(); let len = slice.len();
@ -1450,7 +1450,7 @@ impl From<&str> for Box<str> {
/// ///
/// ```rust /// ```rust
/// let boxed: Box<str> = Box::from("hello"); /// let boxed: Box<str> = Box::from("hello");
/// println!("{}", boxed); /// println!("{boxed}");
/// ``` /// ```
#[inline] #[inline]
fn from(s: &str) -> Box<str> { fn from(s: &str) -> Box<str> {
@ -1475,14 +1475,14 @@ impl From<Cow<'_, str>> for Box<str> {
/// ///
/// let unboxed = Cow::Borrowed("hello"); /// let unboxed = Cow::Borrowed("hello");
/// let boxed: Box<str> = Box::from(unboxed); /// let boxed: Box<str> = Box::from(unboxed);
/// println!("{}", boxed); /// println!("{boxed}");
/// ``` /// ```
/// ///
/// ```rust /// ```rust
/// # use std::borrow::Cow; /// # use std::borrow::Cow;
/// let unboxed = Cow::Owned("hello".to_string()); /// let unboxed = Cow::Owned("hello".to_string());
/// let boxed: Box<str> = Box::from(unboxed); /// let boxed: Box<str> = Box::from(unboxed);
/// println!("{}", boxed); /// println!("{boxed}");
/// ``` /// ```
#[inline] #[inline]
fn from(cow: Cow<'_, str>) -> Box<str> { fn from(cow: Cow<'_, str>) -> Box<str> {
@ -1529,7 +1529,7 @@ impl<T, const N: usize> From<[T; N]> for Box<[T]> {
/// ///
/// ```rust /// ```rust
/// let boxed: Box<[u8]> = Box::from([4, 2]); /// let boxed: Box<[u8]> = Box::from([4, 2]);
/// println!("{:?}", boxed); /// println!("{boxed:?}");
/// ``` /// ```
fn from(array: [T; N]) -> Box<[T]> { fn from(array: [T; N]) -> Box<[T]> {
box array box array

View file

@ -194,7 +194,7 @@ use super::SpecExtend;
/// // We can iterate over the items in the heap, although they are returned in /// // We can iterate over the items in the heap, although they are returned in
/// // a random order. /// // a random order.
/// for x in &heap { /// for x in &heap {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// // If we instead pop these scores, they should come back in order. /// // If we instead pop these scores, they should come back in order.
@ -830,7 +830,7 @@ impl<T> BinaryHeap<T> {
/// ///
/// // Print 1, 2, 3, 4 in arbitrary order /// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.iter() { /// for x in heap.iter() {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -1110,7 +1110,7 @@ impl<T> BinaryHeap<T> {
/// ///
/// // Will print in some order /// // Will print in some order
/// for x in vec { /// for x in vec {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
#[must_use = "`self` will be dropped if the result is not used"] #[must_use = "`self` will be dropped if the result is not used"]
@ -1179,7 +1179,7 @@ impl<T> BinaryHeap<T> {
/// assert!(!heap.is_empty()); /// assert!(!heap.is_empty());
/// ///
/// for x in heap.drain() { /// for x in heap.drain() {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// assert!(heap.is_empty()); /// assert!(heap.is_empty());
@ -1624,7 +1624,7 @@ impl<T> IntoIterator for BinaryHeap<T> {
/// // Print 1, 2, 3, 4 in arbitrary order /// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.into_iter() { /// for x in heap.into_iter() {
/// // x has type i32, not &i32 /// // x has type i32, not &i32
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
fn into_iter(self) -> IntoIter<T> { fn into_iter(self) -> IntoIter<T> {

View file

@ -104,8 +104,8 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
/// let to_find = ["Up!", "Office Space"]; /// let to_find = ["Up!", "Office Space"];
/// for movie in &to_find { /// for movie in &to_find {
/// match movie_reviews.get(movie) { /// match movie_reviews.get(movie) {
/// Some(review) => println!("{}: {}", movie, review), /// Some(review) => println!("{movie}: {review}"),
/// None => println!("{} is unreviewed.", movie) /// None => println!("{movie} is unreviewed.")
/// } /// }
/// } /// }
/// ///
@ -114,7 +114,7 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
/// ///
/// // iterate over everything. /// // iterate over everything.
/// for (movie, review) in &movie_reviews { /// for (movie, review) in &movie_reviews {
/// println!("{}: \"{}\"", movie, review); /// println!("{movie}: \"{review}\"");
/// } /// }
/// ``` /// ```
/// ///
@ -1061,7 +1061,7 @@ impl<K, V> BTreeMap<K, V> {
/// map.insert(5, "b"); /// map.insert(5, "b");
/// map.insert(8, "c"); /// map.insert(8, "c");
/// for (&key, &value) in map.range((Included(&4), Included(&8))) { /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
/// println!("{}: {}", key, value); /// println!("{key}: {value}");
/// } /// }
/// assert_eq!(Some((&5, &"b")), map.range(4..).next()); /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
/// ``` /// ```
@ -1104,7 +1104,7 @@ impl<K, V> BTreeMap<K, V> {
/// *balance += 100; /// *balance += 100;
/// } /// }
/// for (name, balance) in &map { /// for (name, balance) in &map {
/// println!("{} => {}", name, balance); /// println!("{name} => {balance}");
/// } /// }
/// ``` /// ```
#[stable(feature = "btree_range", since = "1.17.0")] #[stable(feature = "btree_range", since = "1.17.0")]
@ -2088,7 +2088,7 @@ impl<K, V> BTreeMap<K, V> {
/// map.insert(1, "a"); /// map.insert(1, "a");
/// ///
/// for (key, value) in map.iter() { /// for (key, value) in map.iter() {
/// println!("{}: {}", key, value); /// println!("{key}: {value}");
/// } /// }
/// ///
/// let (first_key, first_value) = map.iter().next().unwrap(); /// let (first_key, first_value) = map.iter().next().unwrap();

View file

@ -1758,7 +1758,7 @@ fn test_ord_absence() {
} }
fn map_debug<K: Debug>(mut map: BTreeMap<K, ()>) { fn map_debug<K: Debug>(mut map: BTreeMap<K, ()>) {
format!("{:?}", map); format!("{map:?}");
format!("{:?}", map.iter()); format!("{:?}", map.iter());
format!("{:?}", map.iter_mut()); format!("{:?}", map.iter_mut());
format!("{:?}", map.keys()); format!("{:?}", map.keys());

View file

@ -60,7 +60,7 @@ use super::Recover;
/// ///
/// // Iterate over everything. /// // Iterate over everything.
/// for book in &books { /// for book in &books {
/// println!("{}", book); /// println!("{book}");
/// } /// }
/// ``` /// ```
/// ///
@ -284,7 +284,7 @@ impl<T> BTreeSet<T> {
/// set.insert(5); /// set.insert(5);
/// set.insert(8); /// set.insert(8);
/// for &elem in set.range((Included(&4), Included(&8))) { /// for &elem in set.range((Included(&4), Included(&8))) {
/// println!("{}", elem); /// println!("{elem}");
/// } /// }
/// assert_eq!(Some(&5), set.range(4..).next()); /// assert_eq!(Some(&5), set.range(4..).next());
/// ``` /// ```

View file

@ -431,10 +431,10 @@ fn test_show() {
set.insert(1); set.insert(1);
set.insert(2); set.insert(2);
let set_str = format!("{:?}", set); let set_str = format!("{set:?}");
assert_eq!(set_str, "{1, 2}"); assert_eq!(set_str, "{1, 2}");
assert_eq!(format!("{:?}", empty), "{}"); assert_eq!(format!("{empty:?}"), "{}");
} }
#[test] #[test]
@ -649,7 +649,7 @@ fn test_ord_absence() {
} }
fn set_debug<K: Debug>(set: BTreeSet<K>) { fn set_debug<K: Debug>(set: BTreeSet<K>) {
format!("{:?}", set); format!("{set:?}");
format!("{:?}", set.iter()); format!("{:?}", set.iter());
format!("{:?}", set.into_iter()); format!("{:?}", set.into_iter());
} }

View file

@ -416,9 +416,9 @@
//! fn main() { //! fn main() {
//! let myvector = Vector2D { x: 3, y: 4 }; //! let myvector = Vector2D { x: 3, y: 4 };
//! //!
//! println!("{}", myvector); // => "(3, 4)" //! println!("{myvector}"); // => "(3, 4)"
//! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}" //! println!("{myvector:?}"); // => "Vector2D {x: 3, y:4}"
//! println!("{:10.3b}", myvector); // => " 5.000" //! println!("{myvector:10.3b}"); // => " 5.000"
//! } //! }
//! ``` //! ```
//! //!

View file

@ -309,7 +309,7 @@ fn test_cowrc_clone_weak() {
#[test] #[test]
fn test_show() { fn test_show() {
let foo = Rc::new(75); let foo = Rc::new(75);
assert_eq!(format!("{:?}", foo), "75"); assert_eq!(format!("{foo:?}"), "75");
} }
#[test] #[test]
@ -324,7 +324,7 @@ fn test_maybe_thin_unsized() {
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
let x: Rc<CStr> = Rc::from(CString::new("swordfish").unwrap().into_boxed_c_str()); let x: Rc<CStr> = Rc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
assert_eq!(format!("{:?}", x), "\"swordfish\""); assert_eq!(format!("{x:?}"), "\"swordfish\"");
let y: Weak<CStr> = Rc::downgrade(&x); let y: Weak<CStr> = Rc::downgrade(&x);
drop(x); drop(x);
@ -451,7 +451,7 @@ fn test_from_box_trait_zero_sized() {
let b: Box<dyn Debug> = box (); let b: Box<dyn Debug> = box ();
let r: Rc<dyn Debug> = Rc::from(b); let r: Rc<dyn Debug> = Rc::from(b);
assert_eq!(format!("{:?}", r), "()"); assert_eq!(format!("{r:?}"), "()");
} }
#[test] #[test]

View file

@ -48,7 +48,7 @@
//! ``` //! ```
//! let numbers = &[0, 1, 2]; //! let numbers = &[0, 1, 2];
//! for n in numbers { //! for n in numbers {
//! println!("{} is a number!", n); //! println!("{n} is a number!");
//! } //! }
//! ``` //! ```
//! //!

View file

@ -2718,7 +2718,7 @@ impl From<String> for Vec<u8> {
/// let v1 = Vec::from(s1); /// let v1 = Vec::from(s1);
/// ///
/// for b in v1 { /// for b in v1 {
/// println!("{}", b); /// println!("{b}");
/// } /// }
/// ``` /// ```
fn from(string: String) -> Vec<u8> { fn from(string: String) -> Vec<u8> {

View file

@ -200,7 +200,7 @@ macro_rules! acquire {
/// let five = Arc::clone(&five); /// let five = Arc::clone(&five);
/// ///
/// thread::spawn(move || { /// thread::spawn(move || {
/// println!("{:?}", five); /// println!("{five:?}");
/// }); /// });
/// } /// }
/// ``` /// ```
@ -221,7 +221,7 @@ macro_rules! acquire {
/// ///
/// thread::spawn(move || { /// thread::spawn(move || {
/// let v = val.fetch_add(1, Ordering::SeqCst); /// let v = val.fetch_add(1, Ordering::SeqCst);
/// println!("{:?}", v); /// println!("{v:?}");
/// }); /// });
/// } /// }
/// ``` /// ```

View file

@ -335,7 +335,7 @@ fn test_weak_count() {
#[test] #[test]
fn show_arc() { fn show_arc() {
let a = Arc::new(5); let a = Arc::new(5);
assert_eq!(format!("{:?}", a), "5"); assert_eq!(format!("{a:?}"), "5");
} }
// Make sure deriving works with Arc<T> // Make sure deriving works with Arc<T>
@ -347,7 +347,7 @@ struct Foo {
#[test] #[test]
fn test_unsized() { fn test_unsized() {
let x: Arc<[i32]> = Arc::new([1, 2, 3]); let x: Arc<[i32]> = Arc::new([1, 2, 3]);
assert_eq!(format!("{:?}", x), "[1, 2, 3]"); assert_eq!(format!("{x:?}"), "[1, 2, 3]");
let y = Arc::downgrade(&x.clone()); let y = Arc::downgrade(&x.clone());
drop(x); drop(x);
assert!(y.upgrade().is_none()); assert!(y.upgrade().is_none());
@ -359,7 +359,7 @@ fn test_maybe_thin_unsized() {
use std::ffi::{CStr, CString}; use std::ffi::{CStr, CString};
let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str()); let x: Arc<CStr> = Arc::from(CString::new("swordfish").unwrap().into_boxed_c_str());
assert_eq!(format!("{:?}", x), "\"swordfish\""); assert_eq!(format!("{x:?}"), "\"swordfish\"");
let y: Weak<CStr> = Arc::downgrade(&x); let y: Weak<CStr> = Arc::downgrade(&x);
drop(x); drop(x);
@ -509,7 +509,7 @@ fn test_from_box_trait_zero_sized() {
let b: Box<dyn Debug> = box (); let b: Box<dyn Debug> = box ();
let r: Arc<dyn Debug> = Arc::from(b); let r: Arc<dyn Debug> = Arc::from(b);
assert_eq!(format!("{:?}", r), "()"); assert_eq!(format!("{r:?}"), "()");
} }
#[test] #[test]

View file

@ -47,8 +47,8 @@ fn any_move() {
fn test_show() { fn test_show() {
let a = Box::new(8) as Box<dyn Any>; let a = Box::new(8) as Box<dyn Any>;
let b = Box::new(Test) as Box<dyn Any>; let b = Box::new(Test) as Box<dyn Any>;
let a_str = format!("{:?}", a); let a_str = format!("{a:?}");
let b_str = format!("{:?}", b); let b_str = format!("{b:?}");
assert_eq!(a_str, "Any { .. }"); assert_eq!(a_str, "Any { .. }");
assert_eq!(b_str, "Any { .. }"); assert_eq!(b_str, "Any { .. }");
@ -56,9 +56,9 @@ fn test_show() {
static TEST: Test = Test; static TEST: Test = Test;
let a = &EIGHT as &dyn Any; let a = &EIGHT as &dyn Any;
let b = &TEST as &dyn Any; let b = &TEST as &dyn Any;
let s = format!("{:?}", a); let s = format!("{a:?}");
assert_eq!(s, "Any { .. }"); assert_eq!(s, "Any { .. }");
let s = format!("{:?}", b); let s = format!("{b:?}");
assert_eq!(s, "Any { .. }"); assert_eq!(s, "Any { .. }");
} }

View file

@ -169,7 +169,7 @@ mod spec_extend;
/// vec.extend([1, 2, 3].iter().copied()); /// vec.extend([1, 2, 3].iter().copied());
/// ///
/// for x in &vec { /// for x in &vec {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// assert_eq!(vec, [7, 1, 2, 3]); /// assert_eq!(vec, [7, 1, 2, 3]);
/// ``` /// ```
@ -211,7 +211,7 @@ mod spec_extend;
/// ///
/// while let Some(top) = stack.pop() { /// while let Some(top) = stack.pop() {
/// // Prints 3, 2, 1 /// // Prints 3, 2, 1
/// println!("{}", top); /// println!("{top}");
/// } /// }
/// ``` /// ```
/// ///
@ -1297,7 +1297,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold] #[cold]
#[inline(never)] #[inline(never)]
fn assert_failed(index: usize, len: usize) -> ! { fn assert_failed(index: usize, len: usize) -> ! {
panic!("swap_remove index (is {}) should be < len (is {})", index, len); panic!("swap_remove index (is {index}) should be < len (is {len})");
} }
let len = self.len(); let len = self.len();
@ -1338,7 +1338,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold] #[cold]
#[inline(never)] #[inline(never)]
fn assert_failed(index: usize, len: usize) -> ! { fn assert_failed(index: usize, len: usize) -> ! {
panic!("insertion index (is {}) should be <= len (is {})", index, len); panic!("insertion index (is {index}) should be <= len (is {len})");
} }
let len = self.len(); let len = self.len();
@ -1397,7 +1397,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[inline(never)] #[inline(never)]
#[track_caller] #[track_caller]
fn assert_failed(index: usize, len: usize) -> ! { fn assert_failed(index: usize, len: usize) -> ! {
panic!("removal index (is {}) should be < len (is {})", index, len); panic!("removal index (is {index}) should be < len (is {len})");
} }
let len = self.len(); let len = self.len();
@ -1942,7 +1942,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold] #[cold]
#[inline(never)] #[inline(never)]
fn assert_failed(at: usize, len: usize) -> ! { fn assert_failed(at: usize, len: usize) -> ! {
panic!("`at` split index (is {}) should be <= len (is {})", at, len); panic!("`at` split index (is {at}) should be <= len (is {len})");
} }
if at > self.len() { if at > self.len() {
@ -2568,7 +2568,7 @@ impl<T, A: Allocator> IntoIterator for Vec<T, A> {
/// let v = vec!["a".to_string(), "b".to_string()]; /// let v = vec!["a".to_string(), "b".to_string()];
/// for s in v.into_iter() { /// for s in v.into_iter() {
/// // s has type String, not &String /// // s has type String, not &String
/// println!("{}", s); /// println!("{s}");
/// } /// }
/// ``` /// ```
#[inline] #[inline]

View file

@ -84,8 +84,8 @@ fn test_format_macro_interface() {
} }
t!(format!("{:p}", 0x1234 as *const isize), "0x1234"); t!(format!("{:p}", 0x1234 as *const isize), "0x1234");
t!(format!("{:p}", 0x1234 as *mut isize), "0x1234"); t!(format!("{:p}", 0x1234 as *mut isize), "0x1234");
t!(format!("{:x}", A), "aloha"); t!(format!("{A:x}"), "aloha");
t!(format!("{:X}", B), "adios"); t!(format!("{B:X}"), "adios");
t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃"); t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃");
t!(format!("{1} {0}", 0, 1), "1 0"); t!(format!("{1} {0}", 0, 1), "1 0");
t!(format!("{foo} {bar}", foo = 0, bar = 1), "0 1"); t!(format!("{foo} {bar}", foo = 0, bar = 1), "0 1");
@ -94,11 +94,11 @@ fn test_format_macro_interface() {
t!(format!("{_foo}", _foo = 6usize), "6"); t!(format!("{_foo}", _foo = 6usize), "6");
t!(format!("{foo_bar}", foo_bar = 1), "1"); t!(format!("{foo_bar}", foo_bar = 1), "1");
t!(format!("{}", 5 + 5), "10"); t!(format!("{}", 5 + 5), "10");
t!(format!("{:#4}", C), "☃123"); t!(format!("{C:#4}"), "☃123");
t!(format!("{:b}", D), "aa☃bb"); t!(format!("{D:b}"), "aa☃bb");
let a: &dyn fmt::Debug = &1; let a: &dyn fmt::Debug = &1;
t!(format!("{:?}", a), "1"); t!(format!("{a:?}"), "1");
// Formatting strings and their arguments // Formatting strings and their arguments
t!(format!("{}", "a"), "a"); t!(format!("{}", "a"), "a");
@ -206,7 +206,7 @@ fn test_format_macro_interface() {
// Test that pointers don't get truncated. // Test that pointers don't get truncated.
{ {
let val = usize::MAX; let val = usize::MAX;
let exp = format!("{:#x}", val); let exp = format!("{val:#x}");
t!(format!("{:p}", val as *const isize), exp); t!(format!("{:p}", val as *const isize), exp);
} }
@ -216,14 +216,14 @@ fn test_format_macro_interface() {
// make sure that format! doesn't move out of local variables // make sure that format! doesn't move out of local variables
let a = Box::new(3); let a = Box::new(3);
format!("{}", a); format!("{a}");
format!("{}", a); format!("{a}");
// make sure that format! doesn't cause spurious unused-unsafe warnings when // make sure that format! doesn't cause spurious unused-unsafe warnings when
// it's inside of an outer unsafe block // it's inside of an outer unsafe block
unsafe { unsafe {
let a: isize = ::std::mem::transmute(3_usize); let a: isize = ::std::mem::transmute(3_usize);
format!("{}", a); format!("{a}");
} }
// test that trailing commas are acceptable // test that trailing commas are acceptable
@ -315,9 +315,9 @@ fn test_once() {
#[test] #[test]
fn test_refcell() { fn test_refcell() {
let refcell = RefCell::new(5); let refcell = RefCell::new(5);
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }"); assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }");
let borrow = refcell.borrow_mut(); let borrow = refcell.borrow_mut();
assert_eq!(format!("{:?}", refcell), "RefCell { value: <borrowed> }"); assert_eq!(format!("{refcell:?}"), "RefCell { value: <borrowed> }");
drop(borrow); drop(borrow);
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }"); assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }");
} }

View file

@ -302,10 +302,10 @@ fn test_ord_nan() {
#[test] #[test]
fn test_show() { fn test_show() {
let list: LinkedList<_> = (0..10).collect(); let list: LinkedList<_> = (0..10).collect();
assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); assert_eq!(format!("{list:?}"), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let list: LinkedList<_> = ["just", "one", "test", "more"].into_iter().collect(); let list: LinkedList<_> = ["just", "one", "test", "more"].into_iter().collect();
assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]"); assert_eq!(format!("{list:?}"), "[\"just\", \"one\", \"test\", \"more\"]");
} }
#[test] #[test]

View file

@ -1045,10 +1045,10 @@ fn test_split_iterators_size_hint() {
a(v.rsplit_mut(p), b, "rsplit_mut"); a(v.rsplit_mut(p), b, "rsplit_mut");
for n in 0..=3 { for n in 0..=3 {
a(v.splitn(n, p), b, f!("splitn, n = {}", n)); a(v.splitn(n, p), b, f!("splitn, n = {n}"));
a(v.splitn_mut(n, p), b, f!("splitn_mut, n = {}", n)); a(v.splitn_mut(n, p), b, f!("splitn_mut, n = {n}"));
a(v.rsplitn(n, p), b, f!("rsplitn, n = {}", n)); a(v.rsplitn(n, p), b, f!("rsplitn, n = {n}"));
a(v.rsplitn_mut(n, p), b, f!("rsplitn_mut, n = {}", n)); a(v.rsplitn_mut(n, p), b, f!("rsplitn_mut, n = {n}"));
} }
} }
} }
@ -1184,8 +1184,8 @@ fn test_show() {
macro_rules! test_show_vec { macro_rules! test_show_vec {
($x:expr, $x_str:expr) => {{ ($x:expr, $x_str:expr) => {{
let (x, x_str) = ($x, $x_str); let (x, x_str) = ($x, $x_str);
assert_eq!(format!("{:?}", x), x_str); assert_eq!(format!("{x:?}"), x_str);
assert_eq!(format!("{:?}", x), x_str); assert_eq!(format!("{x:?}"), x_str);
}}; }};
} }
let empty = Vec::<i32>::new(); let empty = Vec::<i32>::new();

View file

@ -1259,7 +1259,7 @@ fn test_chars_debug() {
let s = "ศไทย中华Việt Nam"; let s = "ศไทย中华Việt Nam";
let c = s.chars(); let c = s.chars();
assert_eq!( assert_eq!(
format!("{:?}", c), format!("{c:?}"),
r#"Chars(['ศ', 'ไ', 'ท', 'ย', '中', '华', 'V', 'i', 'ệ', 't', ' ', 'N', 'a', 'm'])"# r#"Chars(['ศ', 'ไ', 'ท', 'ย', '中', '华', 'V', 'i', 'ệ', 't', ' ', 'N', 'a', 'm'])"#
); );
} }
@ -1870,7 +1870,7 @@ mod pattern {
} }
if let Some(err) = err { if let Some(err) = err {
panic!("Input skipped range at {}", err); panic!("Input skipped range at {err}");
} }
if first_index != haystack.len() { if first_index != haystack.len() {
@ -2187,10 +2187,10 @@ fn utf8() {
fn check_str_eq(a: String, b: String) { fn check_str_eq(a: String, b: String) {
let mut i: isize = 0; let mut i: isize = 0;
for ab in a.bytes() { for ab in a.bytes() {
println!("{}", i); println!("{i}");
println!("{}", ab); println!("{ab}");
let bb: u8 = b.as_bytes()[i as usize]; let bb: u8 = b.as_bytes()[i as usize];
println!("{}", bb); println!("{bb}");
assert_eq!(ab, bb); assert_eq!(ab, bb);
i += 1; i += 1;
} }

View file

@ -470,7 +470,7 @@ fn test_simple_types() {
#[test] #[test]
fn test_vectors() { fn test_vectors() {
let x: Vec<i32> = vec![]; let x: Vec<i32> = vec![];
assert_eq!(format!("{:?}", x), "[]"); assert_eq!(format!("{x:?}"), "[]");
assert_eq!(format!("{:?}", vec![1]), "[1]"); assert_eq!(format!("{:?}", vec![1]), "[1]");
assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]"); assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) == "[[], [1], [1, 1]]"); assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) == "[[], [1], [1, 1]]");
@ -871,6 +871,6 @@ fn test_from_char() {
fn test_str_concat() { fn test_str_concat() {
let a: String = "hello".to_string(); let a: String = "hello".to_string();
let b: String = "world".to_string(); let b: String = "world".to_string();
let s: String = format!("{}{}", a, b); let s: String = format!("{a}{b}");
assert_eq!(s.as_bytes()[9], 'd' as u8); assert_eq!(s.as_bytes()[9], 'd' as u8);
} }

View file

@ -100,7 +100,7 @@ fn test_debug_fmt() {
assert_eq!("[0, 1]", format!("{:?}", vec2)); assert_eq!("[0, 1]", format!("{:?}", vec2));
let slice: &[isize] = &[4, 5]; let slice: &[isize] = &[4, 5];
assert_eq!("[4, 5]", format!("{:?}", slice)); assert_eq!("[4, 5]", format!("{slice:?}"));
} }
#[test] #[test]
@ -918,7 +918,7 @@ fn test_into_iter_as_mut_slice() {
fn test_into_iter_debug() { fn test_into_iter_debug() {
let vec = vec!['a', 'b', 'c']; let vec = vec!['a', 'b', 'c'];
let into_iter = vec.into_iter(); let into_iter = vec.into_iter();
let debug = format!("{:?}", into_iter); let debug = format!("{into_iter:?}");
assert_eq!(debug, "IntoIter(['a', 'b', 'c'])"); assert_eq!(debug, "IntoIter(['a', 'b', 'c'])");
} }
@ -2336,7 +2336,7 @@ fn test_vec_dedup_panicking() {
let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index); let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index);
if !ok { if !ok {
panic!("expected: {:?}\ngot: {:?}\n", expected, vec); panic!("expected: {expected:?}\ngot: {vec:?}\n");
} }
} }

View file

@ -647,10 +647,10 @@ fn test_ord() {
#[test] #[test]
fn test_show() { fn test_show() {
let ringbuf: VecDeque<_> = (0..10).collect(); let ringbuf: VecDeque<_> = (0..10).collect();
assert_eq!(format!("{:?}", ringbuf), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); assert_eq!(format!("{ringbuf:?}"), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter().cloned().collect(); let ringbuf: VecDeque<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]"); assert_eq!(format!("{ringbuf:?}"), "[\"just\", \"one\", \"test\", \"more\"]");
} }
#[test] #[test]

View file

@ -12,7 +12,7 @@ use test::Bencher;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded { pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 { match decode(v).1 {
FullDecoded::Finite(decoded) => decoded, FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded), full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
} }
} }

View file

@ -6,7 +6,7 @@ use test::Bencher;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded { pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 { match decode(v).1 {
FullDecoded::Finite(decoded) => decoded, FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded), full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
} }
} }

View file

@ -62,7 +62,7 @@
//! println!("String ({}): {}", as_string.len(), as_string); //! println!("String ({}): {}", as_string.len(), as_string);
//! } //! }
//! None => { //! None => {
//! println!("{:?}", value); //! println!("{value:?}");
//! } //! }
//! } //! }
//! } //! }

View file

@ -85,7 +85,7 @@
//! // of scope then the subsequent borrow would cause a dynamic thread panic. //! // of scope then the subsequent borrow would cause a dynamic thread panic.
//! // This is the major hazard of using `RefCell`. //! // This is the major hazard of using `RefCell`.
//! let total: i32 = shared_map.borrow().values().sum(); //! let total: i32 = shared_map.borrow().values().sum();
//! println!("{}", total); //! println!("{total}");
//! } //! }
//! ``` //! ```
//! //!

View file

@ -370,7 +370,7 @@ impl char {
/// ///
/// ``` /// ```
/// for c in '❤'.escape_unicode() { /// for c in '❤'.escape_unicode() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```
@ -448,7 +448,7 @@ impl char {
/// ///
/// ``` /// ```
/// for c in '\n'.escape_debug() { /// for c in '\n'.escape_debug() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```
@ -504,7 +504,7 @@ impl char {
/// ///
/// ``` /// ```
/// for c in '"'.escape_default() { /// for c in '"'.escape_default() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```
@ -949,7 +949,7 @@ impl char {
/// ///
/// ``` /// ```
/// for c in 'İ'.to_lowercase() { /// for c in 'İ'.to_lowercase() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```
@ -1016,7 +1016,7 @@ impl char {
/// ///
/// ``` /// ```
/// for c in 'ß'.to_uppercase() { /// for c in 'ß'.to_uppercase() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```

View file

@ -64,7 +64,7 @@ pub mod rt {
/// ///
/// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 }; /// let pythagorean_triple = Triangle { a: 3.0, b: 4.0, c: 5.0 };
/// ///
/// assert_eq!(format!("{}", pythagorean_triple), "(3, 4, 5)"); /// assert_eq!(format!("{pythagorean_triple}"), "(3, 4, 5)");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub type Result = result::Result<(), Error>; pub type Result = result::Result<(), Error>;
@ -174,7 +174,7 @@ pub trait Write {
/// use std::fmt::{Error, Write}; /// use std::fmt::{Error, Write};
/// ///
/// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> { /// fn writer<W: Write>(f: &mut W, s: &str) -> Result<(), Error> {
/// f.write_fmt(format_args!("{}", s)) /// f.write_fmt(format_args!("{s}"))
/// } /// }
/// ///
/// let mut buf = String::new(); /// let mut buf = String::new();
@ -562,7 +562,7 @@ impl Display for Arguments<'_> {
/// ///
/// let origin = Point { x: 0, y: 0 }; /// let origin = Point { x: 0, y: 0 };
/// ///
/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }"); /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
/// ``` /// ```
/// ///
/// Manually implementing: /// Manually implementing:
@ -586,7 +586,7 @@ impl Display for Arguments<'_> {
/// ///
/// let origin = Point { x: 0, y: 0 }; /// let origin = Point { x: 0, y: 0 };
/// ///
/// assert_eq!(format!("The origin is: {:?}", origin), "The origin is: Point { x: 0, y: 0 }"); /// assert_eq!(format!("The origin is: {origin:?}"), "The origin is: Point { x: 0, y: 0 }");
/// ``` /// ```
/// ///
/// There are a number of helper methods on the [`Formatter`] struct to help you with manual /// There are a number of helper methods on the [`Formatter`] struct to help you with manual
@ -627,7 +627,7 @@ impl Display for Arguments<'_> {
/// ///
/// let origin = Point { x: 0, y: 0 }; /// let origin = Point { x: 0, y: 0 };
/// ///
/// assert_eq!(format!("The origin is: {:#?}", origin), /// assert_eq!(format!("The origin is: {origin:#?}"),
/// "The origin is: Point { /// "The origin is: Point {
/// x: 0, /// x: 0,
/// y: 0, /// y: 0,
@ -670,9 +670,9 @@ pub trait Debug {
/// } /// }
/// ///
/// let position = Position { longitude: 1.987, latitude: 2.983 }; /// let position = Position { longitude: 1.987, latitude: 2.983 };
/// assert_eq!(format!("{:?}", position), "(1.987, 2.983)"); /// assert_eq!(format!("{position:?}"), "(1.987, 2.983)");
/// ///
/// assert_eq!(format!("{:#?}", position), "( /// assert_eq!(format!("{position:#?}"), "(
/// 1.987, /// 1.987,
/// 2.983, /// 2.983,
/// )"); /// )");
@ -724,7 +724,7 @@ pub use macros::Debug;
/// ///
/// let origin = Point { x: 0, y: 0 }; /// let origin = Point { x: 0, y: 0 };
/// ///
/// assert_eq!(format!("The origin is: {}", origin), "The origin is: (0, 0)"); /// assert_eq!(format!("The origin is: {origin}"), "The origin is: (0, 0)");
/// ``` /// ```
#[rustc_on_unimplemented( #[rustc_on_unimplemented(
on( on(
@ -786,8 +786,8 @@ pub trait Display {
/// ``` /// ```
/// let x = 42; // 42 is '52' in octal /// let x = 42; // 42 is '52' in octal
/// ///
/// assert_eq!(format!("{:o}", x), "52"); /// assert_eq!(format!("{x:o}"), "52");
/// assert_eq!(format!("{:#o}", x), "0o52"); /// assert_eq!(format!("{x:#o}"), "0o52");
/// ///
/// assert_eq!(format!("{:o}", -16), "37777777760"); /// assert_eq!(format!("{:o}", -16), "37777777760");
/// ``` /// ```
@ -809,9 +809,9 @@ pub trait Display {
/// ///
/// let l = Length(9); /// let l = Length(9);
/// ///
/// assert_eq!(format!("l as octal is: {:o}", l), "l as octal is: 11"); /// assert_eq!(format!("l as octal is: {l:o}"), "l as octal is: 11");
/// ///
/// assert_eq!(format!("l as octal is: {:#06o}", l), "l as octal is: 0o0011"); /// assert_eq!(format!("l as octal is: {l:#06o}"), "l as octal is: 0o0011");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub trait Octal { pub trait Octal {
@ -840,8 +840,8 @@ pub trait Octal {
/// ``` /// ```
/// let x = 42; // 42 is '101010' in binary /// let x = 42; // 42 is '101010' in binary
/// ///
/// assert_eq!(format!("{:b}", x), "101010"); /// assert_eq!(format!("{x:b}"), "101010");
/// assert_eq!(format!("{:#b}", x), "0b101010"); /// assert_eq!(format!("{x:#b}"), "0b101010");
/// ///
/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000"); /// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
/// ``` /// ```
@ -863,10 +863,10 @@ pub trait Octal {
/// ///
/// let l = Length(107); /// let l = Length(107);
/// ///
/// assert_eq!(format!("l as binary is: {:b}", l), "l as binary is: 1101011"); /// assert_eq!(format!("l as binary is: {l:b}"), "l as binary is: 1101011");
/// ///
/// assert_eq!( /// assert_eq!(
/// format!("l as binary is: {:#032b}", l), /// format!("l as binary is: {l:#032b}"),
/// "l as binary is: 0b000000000000000000000001101011" /// "l as binary is: 0b000000000000000000000001101011"
/// ); /// );
/// ``` /// ```
@ -898,8 +898,8 @@ pub trait Binary {
/// ``` /// ```
/// let x = 42; // 42 is '2a' in hex /// let x = 42; // 42 is '2a' in hex
/// ///
/// assert_eq!(format!("{:x}", x), "2a"); /// assert_eq!(format!("{x:x}"), "2a");
/// assert_eq!(format!("{:#x}", x), "0x2a"); /// assert_eq!(format!("{x:#x}"), "0x2a");
/// ///
/// assert_eq!(format!("{:x}", -16), "fffffff0"); /// assert_eq!(format!("{:x}", -16), "fffffff0");
/// ``` /// ```
@ -921,9 +921,9 @@ pub trait Binary {
/// ///
/// let l = Length(9); /// let l = Length(9);
/// ///
/// assert_eq!(format!("l as hex is: {:x}", l), "l as hex is: 9"); /// assert_eq!(format!("l as hex is: {l:x}"), "l as hex is: 9");
/// ///
/// assert_eq!(format!("l as hex is: {:#010x}", l), "l as hex is: 0x00000009"); /// assert_eq!(format!("l as hex is: {l:#010x}"), "l as hex is: 0x00000009");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub trait LowerHex { pub trait LowerHex {
@ -953,8 +953,8 @@ pub trait LowerHex {
/// ``` /// ```
/// let x = 42; // 42 is '2A' in hex /// let x = 42; // 42 is '2A' in hex
/// ///
/// assert_eq!(format!("{:X}", x), "2A"); /// assert_eq!(format!("{x:X}"), "2A");
/// assert_eq!(format!("{:#X}", x), "0x2A"); /// assert_eq!(format!("{x:#X}"), "0x2A");
/// ///
/// assert_eq!(format!("{:X}", -16), "FFFFFFF0"); /// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
/// ``` /// ```
@ -976,9 +976,9 @@ pub trait LowerHex {
/// ///
/// let l = Length(i32::MAX); /// let l = Length(i32::MAX);
/// ///
/// assert_eq!(format!("l as hex is: {:X}", l), "l as hex is: 7FFFFFFF"); /// assert_eq!(format!("l as hex is: {l:X}"), "l as hex is: 7FFFFFFF");
/// ///
/// assert_eq!(format!("l as hex is: {:#010X}", l), "l as hex is: 0x7FFFFFFF"); /// assert_eq!(format!("l as hex is: {l:#010X}"), "l as hex is: 0x7FFFFFFF");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub trait UpperHex { pub trait UpperHex {
@ -1003,7 +1003,7 @@ pub trait UpperHex {
/// ``` /// ```
/// let x = &42; /// let x = &42;
/// ///
/// let address = format!("{:p}", x); // this produces something like '0x7f06092ac6d0' /// let address = format!("{x:p}"); // this produces something like '0x7f06092ac6d0'
/// ``` /// ```
/// ///
/// Implementing `Pointer` on a type: /// Implementing `Pointer` on a type:
@ -1024,9 +1024,9 @@ pub trait UpperHex {
/// ///
/// let l = Length(42); /// let l = Length(42);
/// ///
/// println!("l is in memory here: {:p}", l); /// println!("l is in memory here: {l:p}");
/// ///
/// let l_ptr = format!("{:018p}", l); /// let l_ptr = format!("{l:018p}");
/// assert_eq!(l_ptr.len(), 18); /// assert_eq!(l_ptr.len(), 18);
/// assert_eq!(&l_ptr[..2], "0x"); /// assert_eq!(&l_ptr[..2], "0x");
/// ``` /// ```
@ -1054,7 +1054,7 @@ pub trait Pointer {
/// ``` /// ```
/// let x = 42.0; // 42.0 is '4.2e1' in scientific notation /// let x = 42.0; // 42.0 is '4.2e1' in scientific notation
/// ///
/// assert_eq!(format!("{:e}", x), "4.2e1"); /// assert_eq!(format!("{x:e}"), "4.2e1");
/// ``` /// ```
/// ///
/// Implementing `LowerExp` on a type: /// Implementing `LowerExp` on a type:
@ -1074,12 +1074,12 @@ pub trait Pointer {
/// let l = Length(100); /// let l = Length(100);
/// ///
/// assert_eq!( /// assert_eq!(
/// format!("l in scientific notation is: {:e}", l), /// format!("l in scientific notation is: {l:e}"),
/// "l in scientific notation is: 1e2" /// "l in scientific notation is: 1e2"
/// ); /// );
/// ///
/// assert_eq!( /// assert_eq!(
/// format!("l in scientific notation is: {:05e}", l), /// format!("l in scientific notation is: {l:05e}"),
/// "l in scientific notation is: 001e2" /// "l in scientific notation is: 001e2"
/// ); /// );
/// ``` /// ```
@ -1105,7 +1105,7 @@ pub trait LowerExp {
/// ``` /// ```
/// let x = 42.0; // 42.0 is '4.2E1' in scientific notation /// let x = 42.0; // 42.0 is '4.2E1' in scientific notation
/// ///
/// assert_eq!(format!("{:E}", x), "4.2E1"); /// assert_eq!(format!("{x:E}"), "4.2E1");
/// ``` /// ```
/// ///
/// Implementing `UpperExp` on a type: /// Implementing `UpperExp` on a type:
@ -1125,12 +1125,12 @@ pub trait LowerExp {
/// let l = Length(100); /// let l = Length(100);
/// ///
/// assert_eq!( /// assert_eq!(
/// format!("l in scientific notation is: {:E}", l), /// format!("l in scientific notation is: {l:E}"),
/// "l in scientific notation is: 1E2" /// "l in scientific notation is: 1E2"
/// ); /// );
/// ///
/// assert_eq!( /// assert_eq!(
/// format!("l in scientific notation is: {:05E}", l), /// format!("l in scientific notation is: {l:05E}"),
/// "l in scientific notation is: 001E2" /// "l in scientific notation is: 001E2"
/// ); /// );
/// ``` /// ```
@ -1429,8 +1429,8 @@ impl<'a> Formatter<'a> {
/// } /// }
/// } /// }
/// ///
/// assert_eq!(&format!("{:<4}", Foo), "Foo "); /// assert_eq!(&format!("{Foo:<4}"), "Foo ");
/// assert_eq!(&format!("{:0>4}", Foo), "0Foo"); /// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn pad(&mut self, s: &str) -> Result { pub fn pad(&mut self, s: &str) -> Result {
@ -1613,8 +1613,8 @@ impl<'a> Formatter<'a> {
/// } /// }
/// } /// }
/// ///
/// assert_eq!(&format!("{}", Foo), "Foo"); /// assert_eq!(&format!("{Foo}"), "Foo");
/// assert_eq!(&format!("{:0>8}", Foo), "Foo"); /// assert_eq!(&format!("{Foo:0>8}"), "Foo");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn write_str(&mut self, data: &str) -> Result { pub fn write_str(&mut self, data: &str) -> Result {
@ -1670,18 +1670,18 @@ impl<'a> Formatter<'a> {
/// let c = formatter.fill(); /// let c = formatter.fill();
/// if let Some(width) = formatter.width() { /// if let Some(width) = formatter.width() {
/// for _ in 0..width { /// for _ in 0..width {
/// write!(formatter, "{}", c)?; /// write!(formatter, "{c}")?;
/// } /// }
/// Ok(()) /// Ok(())
/// } else { /// } else {
/// write!(formatter, "{}", c) /// write!(formatter, "{c}")
/// } /// }
/// } /// }
/// } /// }
/// ///
/// // We set alignment to the right with ">". /// // We set alignment to the right with ">".
/// assert_eq!(&format!("{:G>3}", Foo), "GGG"); /// assert_eq!(&format!("{Foo:G>3}"), "GGG");
/// assert_eq!(&format!("{:t>6}", Foo), "tttttt"); /// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
/// ``` /// ```
#[must_use] #[must_use]
#[stable(feature = "fmt_flags", since = "1.5.0")] #[stable(feature = "fmt_flags", since = "1.5.0")]
@ -1711,14 +1711,14 @@ impl<'a> Formatter<'a> {
/// } else { /// } else {
/// "into the void" /// "into the void"
/// }; /// };
/// write!(formatter, "{}", s) /// write!(formatter, "{s}")
/// } /// }
/// } /// }
/// ///
/// assert_eq!(&format!("{:<}", Foo), "left"); /// assert_eq!(&format!("{Foo:<}"), "left");
/// assert_eq!(&format!("{:>}", Foo), "right"); /// assert_eq!(&format!("{Foo:>}"), "right");
/// assert_eq!(&format!("{:^}", Foo), "center"); /// assert_eq!(&format!("{Foo:^}"), "center");
/// assert_eq!(&format!("{}", Foo), "into the void"); /// assert_eq!(&format!("{Foo}"), "into the void");
/// ``` /// ```
#[must_use] #[must_use]
#[stable(feature = "fmt_flags_align", since = "1.28.0")] #[stable(feature = "fmt_flags_align", since = "1.28.0")]

View file

@ -34,7 +34,7 @@ use crate::ops::Try;
/// ///
/// for pair in ['a', 'b', 'c'].into_iter() /// for pair in ['a', 'b', 'c'].into_iter()
/// .map(|letter| { c += 1; (letter, c) }) { /// .map(|letter| { c += 1; (letter, c) }) {
/// println!("{:?}", pair); /// println!("{pair:?}");
/// } /// }
/// ``` /// ```
/// ///
@ -52,7 +52,7 @@ use crate::ops::Try;
/// for pair in ['a', 'b', 'c'].into_iter() /// for pair in ['a', 'b', 'c'].into_iter()
/// .map(|letter| { c += 1; (letter, c) }) /// .map(|letter| { c += 1; (letter, c) })
/// .rev() { /// .rev() {
/// println!("{:?}", pair); /// println!("{pair:?}");
/// } /// }
/// ``` /// ```
#[must_use = "iterators are lazy and do nothing unless consumed"] #[must_use = "iterators are lazy and do nothing unless consumed"]

View file

@ -144,7 +144,7 @@
//! let values = vec![1, 2, 3, 4, 5]; //! let values = vec![1, 2, 3, 4, 5];
//! //!
//! for x in values { //! for x in values {
//! println!("{}", x); //! println!("{x}");
//! } //! }
//! ``` //! ```
//! //!
@ -164,7 +164,7 @@
//! let values = vec![1, 2, 3, 4, 5]; //! let values = vec![1, 2, 3, 4, 5];
//! //!
//! for x in values { //! for x in values {
//! println!("{}", x); //! println!("{x}");
//! } //! }
//! ``` //! ```
//! //!
@ -181,7 +181,7 @@
//! None => break, //! None => break,
//! }; //! };
//! let x = next; //! let x = next;
//! let () = { println!("{}", x); }; //! let () = { println!("{x}"); };
//! }, //! },
//! }; //! };
//! result //! result
@ -280,7 +280,7 @@
//! ``` //! ```
//! # #![allow(unused_must_use)] //! # #![allow(unused_must_use)]
//! let v = vec![1, 2, 3, 4, 5]; //! let v = vec![1, 2, 3, 4, 5];
//! v.iter().map(|x| println!("{}", x)); //! v.iter().map(|x| println!("{x}"));
//! ``` //! ```
//! //!
//! This will not print any values, as we only created an iterator, rather than //! This will not print any values, as we only created an iterator, rather than
@ -297,10 +297,10 @@
//! ``` //! ```
//! let v = vec![1, 2, 3, 4, 5]; //! let v = vec![1, 2, 3, 4, 5];
//! //!
//! v.iter().for_each(|x| println!("{}", x)); //! v.iter().for_each(|x| println!("{x}"));
//! // or //! // or
//! for x in &v { //! for x in &v {
//! println!("{}", x); //! println!("{x}");
//! } //! }
//! ``` //! ```
//! //!
@ -329,7 +329,7 @@
//! let five_numbers = numbers.take(5); //! let five_numbers = numbers.take(5);
//! //!
//! for number in five_numbers { //! for number in five_numbers {
//! println!("{}", number); //! println!("{number}");
//! } //! }
//! ``` //! ```
//! //!
@ -345,7 +345,7 @@
//! let ones = std::iter::repeat(1); //! let ones = std::iter::repeat(1);
//! let least = ones.min().unwrap(); // Oh no! An infinite loop! //! let least = ones.min().unwrap(); // Oh no! An infinite loop!
//! // `ones.min()` causes an infinite loop, so we won't reach this point! //! // `ones.min()` causes an infinite loop, so we won't reach this point!
//! println!("The smallest number one is {}.", least); //! println!("The smallest number one is {least}.");
//! ``` //! ```
//! //!
//! [`take`]: Iterator::take //! [`take`]: Iterator::take

View file

@ -48,7 +48,7 @@ use crate::iter::{FusedIterator, TrustedLen};
/// ///
/// // this will give us all of the files in .foo as well as .foorc /// // this will give us all of the files in .foo as well as .foorc
/// for f in files { /// for f in files {
/// println!("{:?}", f); /// println!("{f:?}");
/// } /// }
/// ``` /// ```
#[stable(feature = "iter_once", since = "1.2.0")] #[stable(feature = "iter_once", since = "1.2.0")]

View file

@ -52,7 +52,7 @@ use crate::iter::{FusedIterator, TrustedLen};
/// ///
/// // this will give us all of the files in .foo as well as .foorc /// // this will give us all of the files in .foo as well as .foorc
/// for f in files { /// for f in files {
/// println!("{:?}", f); /// println!("{f:?}");
/// } /// }
/// ``` /// ```
#[inline] #[inline]

View file

@ -214,7 +214,7 @@ pub trait FromIterator<A>: Sized {
/// { /// {
/// collection /// collection
/// .into_iter() /// .into_iter()
/// .map(|item| format!("{:?}", item)) /// .map(|item| format!("{item:?}"))
/// .collect() /// .collect()
/// } /// }
/// ``` /// ```
@ -332,7 +332,7 @@ impl<I: Iterator> IntoIterator for I {
/// c.extend(vec![1, 2, 3]); /// c.extend(vec![1, 2, 3]);
/// ///
/// // we've added these elements onto the end /// // we've added these elements onto the end
/// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{:?}", c)); /// assert_eq!("MyCollection([5, 6, 7, 1, 2, 3])", format!("{c:?}"));
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub trait Extend<A> { pub trait Extend<A> {

View file

@ -281,7 +281,7 @@ pub trait DoubleEndedIterator: Iterator {
/// let zero = "0".to_string(); /// let zero = "0".to_string();
/// ///
/// let result = numbers.iter().rfold(zero, |acc, &x| { /// let result = numbers.iter().rfold(zero, |acc, &x| {
/// format!("({} + {})", x, acc) /// format!("({x} + {acc})")
/// }); /// });
/// ///
/// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))"); /// assert_eq!(result, "(1 + (2 + (3 + (4 + (5 + 0)))))");

View file

@ -709,13 +709,13 @@ pub trait Iterator {
/// ``` /// ```
/// # #![allow(unused_must_use)] /// # #![allow(unused_must_use)]
/// // don't do this: /// // don't do this:
/// (0..5).map(|x| println!("{}", x)); /// (0..5).map(|x| println!("{x}"));
/// ///
/// // it won't even execute, as it is lazy. Rust will warn you about this. /// // it won't even execute, as it is lazy. Rust will warn you about this.
/// ///
/// // Instead, use for: /// // Instead, use for:
/// for x in 0..5 { /// for x in 0..5 {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
#[inline] #[inline]
@ -761,7 +761,7 @@ pub trait Iterator {
/// (0..5).flat_map(|x| x * 100 .. x * 110) /// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate() /// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0) /// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x)); /// .for_each(|(i, x)| println!("{i}:{x}"));
/// ``` /// ```
#[inline] #[inline]
#[stable(feature = "iterator_for_each", since = "1.21.0")] #[stable(feature = "iterator_for_each", since = "1.21.0")]
@ -1575,17 +1575,17 @@ pub trait Iterator {
/// .filter(|x| x % 2 == 0) /// .filter(|x| x % 2 == 0)
/// .fold(0, |sum, i| sum + i); /// .fold(0, |sum, i| sum + i);
/// ///
/// println!("{}", sum); /// println!("{sum}");
/// ///
/// // let's add some inspect() calls to investigate what's happening /// // let's add some inspect() calls to investigate what's happening
/// let sum = a.iter() /// let sum = a.iter()
/// .cloned() /// .cloned()
/// .inspect(|x| println!("about to filter: {}", x)) /// .inspect(|x| println!("about to filter: {x}"))
/// .filter(|x| x % 2 == 0) /// .filter(|x| x % 2 == 0)
/// .inspect(|x| println!("made it through filter: {}", x)) /// .inspect(|x| println!("made it through filter: {x}"))
/// .fold(0, |sum, i| sum + i); /// .fold(0, |sum, i| sum + i);
/// ///
/// println!("{}", sum); /// println!("{sum}");
/// ``` /// ```
/// ///
/// This will print: /// This will print:
@ -1611,13 +1611,13 @@ pub trait Iterator {
/// .map(|line| line.parse::<i32>()) /// .map(|line| line.parse::<i32>())
/// .inspect(|num| { /// .inspect(|num| {
/// if let Err(ref e) = *num { /// if let Err(ref e) = *num {
/// println!("Parsing error: {}", e); /// println!("Parsing error: {e}");
/// } /// }
/// }) /// })
/// .filter_map(Result::ok) /// .filter_map(Result::ok)
/// .sum(); /// .sum();
/// ///
/// println!("Sum: {}", sum); /// println!("Sum: {sum}");
/// ``` /// ```
/// ///
/// This will print: /// This will print:
@ -2205,7 +2205,7 @@ pub trait Iterator {
/// ///
/// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"]; /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
/// ///
/// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x)); /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{x}"));
/// assert!(res.is_ok()); /// assert!(res.is_ok());
/// ///
/// let mut it = data.iter().cloned(); /// let mut it = data.iter().cloned();
@ -2319,7 +2319,7 @@ pub trait Iterator {
/// let zero = "0".to_string(); /// let zero = "0".to_string();
/// ///
/// let result = numbers.iter().fold(zero, |acc, &x| { /// let result = numbers.iter().fold(zero, |acc, &x| {
/// format!("({} + {})", acc, x) /// format!("({acc} + {x})")
/// }); /// });
/// ///
/// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)"); /// assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)");

View file

@ -895,7 +895,7 @@ pub(crate) mod builtin {
/// ///
/// ``` /// ```
/// let path: &'static str = env!("PATH"); /// let path: &'static str = env!("PATH");
/// println!("the $PATH variable at the time of compiling was: {}", path); /// println!("the $PATH variable at the time of compiling was: {path}");
/// ``` /// ```
/// ///
/// You can customize the error message by passing a string as the second /// You can customize the error message by passing a string as the second
@ -935,7 +935,7 @@ pub(crate) mod builtin {
/// ///
/// ``` /// ```
/// let key: Option<&'static str> = option_env!("SECRET_KEY"); /// let key: Option<&'static str> = option_env!("SECRET_KEY");
/// println!("the secret key might be: {:?}", key); /// println!("the secret key might be: {key:?}");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro] #[rustc_builtin_macro]
@ -1046,7 +1046,7 @@ pub(crate) mod builtin {
/// ///
/// ``` /// ```
/// let current_line = line!(); /// let current_line = line!();
/// println!("defined on line: {}", current_line); /// println!("defined on line: {current_line}");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro] #[rustc_builtin_macro]
@ -1074,7 +1074,7 @@ pub(crate) mod builtin {
/// ///
/// ``` /// ```
/// let current_col = column!(); /// let current_col = column!();
/// println!("defined on column: {}", current_col); /// println!("defined on column: {current_col}");
/// ``` /// ```
/// ///
/// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two /// `column!` counts Unicode code points, not bytes or graphemes. As a result, the first two
@ -1112,7 +1112,7 @@ pub(crate) mod builtin {
/// ///
/// ``` /// ```
/// let this_file = file!(); /// let this_file = file!();
/// println!("defined in file: {}", this_file); /// println!("defined in file: {this_file}");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro] #[rustc_builtin_macro]
@ -1176,7 +1176,7 @@ pub(crate) mod builtin {
/// fn main() { /// fn main() {
/// let my_str = include_str!("spanish.in"); /// let my_str = include_str!("spanish.in");
/// assert_eq!(my_str, "adiós\n"); /// assert_eq!(my_str, "adiós\n");
/// print!("{}", my_str); /// print!("{my_str}");
/// } /// }
/// ``` /// ```
/// ///
@ -1325,7 +1325,7 @@ pub(crate) mod builtin {
/// fn main() { /// fn main() {
/// let my_string = include!("monkeys.in"); /// let my_string = include!("monkeys.in");
/// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string); /// assert_eq!("🙈🙊🙉🙈🙊🙉", my_string);
/// println!("{}", my_string); /// println!("{my_string}");
/// } /// }
/// ``` /// ```
/// ///

View file

@ -219,7 +219,7 @@ pub trait StructuralEq {
/// ///
/// // `x` has moved into `y`, and so cannot be used /// // `x` has moved into `y`, and so cannot be used
/// ///
/// // println!("{:?}", x); // error: use of moved value /// // println!("{x:?}"); // error: use of moved value
/// ``` /// ```
/// ///
/// However, if a type implements `Copy`, it instead has 'copy semantics': /// However, if a type implements `Copy`, it instead has 'copy semantics':
@ -236,7 +236,7 @@ pub trait StructuralEq {
/// ///
/// // `y` is a copy of `x` /// // `y` is a copy of `x`
/// ///
/// println!("{:?}", x); // A-OK! /// println!("{x:?}"); // A-OK!
/// ``` /// ```
/// ///
/// It's important to note that in these two examples, the only difference is whether you /// It's important to note that in these two examples, the only difference is whether you

View file

@ -163,7 +163,7 @@ from_str_float_impl!(f64);
/// use std::str::FromStr; /// use std::str::FromStr;
/// ///
/// if let Err(e) = f64::from_str("a.12") { /// if let Err(e) = f64::from_str("a.12") {
/// println!("Failed conversion to f64: {}", e); /// println!("Failed conversion to f64: {e}");
/// } /// }
/// ``` /// ```
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]

View file

@ -61,7 +61,7 @@ impl const From<!> for TryFromIntError {
/// ///
/// ``` /// ```
/// if let Err(e) = i32::from_str_radix("a12", 10) { /// if let Err(e) = i32::from_str_radix("a12", 10) {
/// println!("Failed conversion to i32: {}", e); /// println!("Failed conversion to i32: {e}");
/// } /// }
/// ``` /// ```
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]

View file

@ -106,7 +106,7 @@ pub trait Index<Idx: ?Sized> {
/// type Output = Weight; /// type Output = Weight;
/// ///
/// fn index(&self, index: Side) -> &Self::Output { /// fn index(&self, index: Side) -> &Self::Output {
/// println!("Accessing {:?}-side of balance immutably", index); /// println!("Accessing {index:?}-side of balance immutably");
/// match index { /// match index {
/// Side::Left => &self.left, /// Side::Left => &self.left,
/// Side::Right => &self.right, /// Side::Right => &self.right,
@ -116,7 +116,7 @@ pub trait Index<Idx: ?Sized> {
/// ///
/// impl IndexMut<Side> for Balance { /// impl IndexMut<Side> for Balance {
/// fn index_mut(&mut self, index: Side) -> &mut Self::Output { /// fn index_mut(&mut self, index: Side) -> &mut Self::Output {
/// println!("Accessing {:?}-side of balance mutably", index); /// println!("Accessing {index:?}-side of balance mutably");
/// match index { /// match index {
/// Side::Left => &mut self.left, /// Side::Left => &mut self.left,
/// Side::Right => &mut self.right, /// Side::Right => &mut self.right,

View file

@ -653,7 +653,7 @@ impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
/// map.insert(8, "c"); /// map.insert(8, "c");
/// ///
/// for (key, value) in map.range((Excluded(3), Included(8))) { /// for (key, value) in map.range((Excluded(3), Included(8))) {
/// println!("{}: {}", key, value); /// println!("{key}: {value}");
/// } /// }
/// ///
/// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next()); /// assert_eq!(Some((&3, &"a")), map.range((Unbounded, Included(5))).next());

View file

@ -34,7 +34,7 @@
//! // Pattern match to retrieve the value //! // Pattern match to retrieve the value
//! match result { //! match result {
//! // The division was valid //! // The division was valid
//! Some(x) => println!("Result: {}", x), //! Some(x) => println!("Result: {x}"),
//! // The division was invalid //! // The division was invalid
//! None => println!("Cannot divide by 0"), //! None => println!("Cannot divide by 0"),
//! } //! }
@ -66,7 +66,7 @@
//! //!
//! fn check_optional(optional: Option<Box<i32>>) { //! fn check_optional(optional: Option<Box<i32>>) {
//! match optional { //! match optional {
//! Some(p) => println!("has value {}", p), //! Some(p) => println!("has value {p}"),
//! None => println!("has no value"), //! None => println!("has no value"),
//! } //! }
//! } //! }
@ -493,7 +493,7 @@
//! } //! }
//! //!
//! match name_of_biggest_animal { //! match name_of_biggest_animal {
//! Some(name) => println!("the biggest animal is {}", name), //! Some(name) => println!("the biggest animal is {name}"),
//! None => println!("there are no animals :("), //! None => println!("there are no animals :("),
//! } //! }
//! ``` //! ```
@ -615,7 +615,7 @@ impl<T> Option<T> {
/// // First, cast `Option<String>` to `Option<&String>` with `as_ref`, /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
/// // then consume *that* with `map`, leaving `text` on the stack. /// // then consume *that* with `map`, leaving `text` on the stack.
/// let text_length: Option<usize> = text.as_ref().map(|s| s.len()); /// let text_length: Option<usize> = text.as_ref().map(|s| s.len());
/// println!("still can print text: {:?}", text); /// println!("still can print text: {text:?}");
/// ``` /// ```
#[inline] #[inline]
#[rustc_const_stable(feature = "const_option", since = "1.48.0")] #[rustc_const_stable(feature = "const_option", since = "1.48.0")]
@ -918,10 +918,10 @@ impl<T> Option<T> {
/// let v = vec![1, 2, 3, 4, 5]; /// let v = vec![1, 2, 3, 4, 5];
/// ///
/// // prints "got: 4" /// // prints "got: 4"
/// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {}", x)); /// let x: Option<&usize> = v.get(3).inspect(|x| println!("got: {x}"));
/// ///
/// // prints nothing /// // prints nothing
/// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {}", x)); /// let x: Option<&usize> = v.get(5).inspect(|x| println!("got: {x}"));
/// ``` /// ```
#[inline] #[inline]
#[unstable(feature = "result_option_inspect", issue = "91345")] #[unstable(feature = "result_option_inspect", issue = "91345")]
@ -1976,7 +1976,7 @@ impl<'a, T> const From<&'a Option<T>> for Option<&'a T> {
/// let s: Option<String> = Some(String::from("Hello, Rustaceans!")); /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
/// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len()); /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
/// ///
/// println!("Can still print s: {:?}", s); /// println!("Can still print s: {s:?}");
/// ///
/// assert_eq!(o, Some(18)); /// assert_eq!(o, Some(18));
/// ``` /// ```

View file

@ -16,7 +16,7 @@ use crate::panic::Location;
/// ///
/// panic::set_hook(Box::new(|panic_info| { /// panic::set_hook(Box::new(|panic_info| {
/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() { /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
/// println!("panic occurred: {:?}", s); /// println!("panic occurred: {s:?}");
/// } else { /// } else {
/// println!("panic occurred"); /// println!("panic occurred");
/// } /// }
@ -75,7 +75,7 @@ impl<'a> PanicInfo<'a> {
/// ///
/// panic::set_hook(Box::new(|panic_info| { /// panic::set_hook(Box::new(|panic_info| {
/// if let Some(s) = panic_info.payload().downcast_ref::<&str>() { /// if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
/// println!("panic occurred: {:?}", s); /// println!("panic occurred: {s:?}");
/// } else { /// } else {
/// println!("panic occurred"); /// println!("panic occurred");
/// } /// }

View file

@ -39,7 +39,7 @@ use crate::panic::{Location, PanicInfo};
#[rustc_const_unstable(feature = "core_panic", issue = "none")] #[rustc_const_unstable(feature = "core_panic", issue = "none")]
#[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
pub const fn panic(expr: &'static str) -> ! { pub const fn panic(expr: &'static str) -> ! {
// Use Arguments::new_v1 instead of format_args!("{}", expr) to potentially // Use Arguments::new_v1 instead of format_args!("{expr}") to potentially
// reduce size overhead. The format_args! macro uses str's Display trait to // reduce size overhead. The format_args! macro uses str's Display trait to
// write expr, which calls Formatter::pad, which must accommodate string // write expr, which calls Formatter::pad, which must accommodate string
// truncation and padding (even though none is used here). Using // truncation and padding (even though none is used here). Using
@ -81,7 +81,7 @@ fn panic_bounds_check(index: usize, len: usize) -> ! {
super::intrinsics::abort() super::intrinsics::abort()
} }
panic!("index out of bounds: the len is {} but the index is {}", len, index) panic!("index out of bounds: the len is {len} but the index is {index}")
} }
// This function is called directly by the codegen backend, and must not have // This function is called directly by the codegen backend, and must not have

View file

@ -607,7 +607,7 @@ mod prim_pointer {}
/// ///
/// // This loop prints: 0 1 2 /// // This loop prints: 0 1 2
/// for x in array { /// for x in array {
/// print!("{} ", x); /// print!("{x} ");
/// } /// }
/// ``` /// ```
/// ///
@ -646,19 +646,19 @@ mod prim_pointer {}
/// // This creates a slice iterator, producing references to each value. /// // This creates a slice iterator, producing references to each value.
/// for item in array.into_iter().enumerate() { /// for item in array.into_iter().enumerate() {
/// let (i, x): (usize, &i32) = item; /// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x); /// println!("array[{i}] = {x}");
/// } /// }
/// ///
/// // The `array_into_iter` lint suggests this change for future compatibility: /// // The `array_into_iter` lint suggests this change for future compatibility:
/// for item in array.iter().enumerate() { /// for item in array.iter().enumerate() {
/// let (i, x): (usize, &i32) = item; /// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x); /// println!("array[{i}] = {x}");
/// } /// }
/// ///
/// // You can explicitly iterate an array by value using `IntoIterator::into_iter` /// // You can explicitly iterate an array by value using `IntoIterator::into_iter`
/// for item in IntoIterator::into_iter(array).enumerate() { /// for item in IntoIterator::into_iter(array).enumerate() {
/// let (i, x): (usize, i32) = item; /// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x); /// println!("array[{i}] = {x}");
/// } /// }
/// ``` /// ```
/// ///
@ -673,13 +673,13 @@ mod prim_pointer {}
/// // This iterates by reference: /// // This iterates by reference:
/// for item in array.iter().enumerate() { /// for item in array.iter().enumerate() {
/// let (i, x): (usize, &i32) = item; /// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x); /// println!("array[{i}] = {x}");
/// } /// }
/// ///
/// // This iterates by value: /// // This iterates by value:
/// for item in array.into_iter().enumerate() { /// for item in array.into_iter().enumerate() {
/// let (i, x): (usize, i32) = item; /// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x); /// println!("array[{i}] = {x}");
/// } /// }
/// ``` /// ```
/// ///
@ -702,26 +702,26 @@ mod prim_pointer {}
/// // This iterates by reference: /// // This iterates by reference:
/// for item in array.iter() { /// for item in array.iter() {
/// let x: &i32 = item; /// let x: &i32 = item;
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// // This iterates by value: /// // This iterates by value:
/// for item in IntoIterator::into_iter(array) { /// for item in IntoIterator::into_iter(array) {
/// let x: i32 = item; /// let x: i32 = item;
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// // This iterates by value: /// // This iterates by value:
/// for item in array { /// for item in array {
/// let x: i32 = item; /// let x: i32 = item;
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// // IntoIter can also start a chain. /// // IntoIter can also start a chain.
/// // This iterates by value: /// // This iterates by value:
/// for item in IntoIterator::into_iter(array).enumerate() { /// for item in IntoIterator::into_iter(array).enumerate() {
/// let (i, x): (usize, i32) = item; /// let (i, x): (usize, i32) = item;
/// println!("array[{}] = {}", i, x); /// println!("array[{i}] = {x}");
/// } /// }
/// ``` /// ```
/// ///

View file

@ -153,7 +153,7 @@ impl<T: ?Sized> *const T {
/// ///
/// unsafe { /// unsafe {
/// if let Some(val_back) = ptr.as_ref() { /// if let Some(val_back) = ptr.as_ref() {
/// println!("We got back the value: {}!", val_back); /// println!("We got back the value: {val_back}!");
/// } /// }
/// } /// }
/// ``` /// ```
@ -169,7 +169,7 @@ impl<T: ?Sized> *const T {
/// ///
/// unsafe { /// unsafe {
/// let val_back = &*ptr; /// let val_back = &*ptr;
/// println!("We got back the value: {}!", val_back); /// println!("We got back the value: {val_back}!");
/// } /// }
/// ``` /// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")] #[stable(feature = "ptr_as_ref", since = "1.9.0")]

View file

@ -160,7 +160,7 @@ impl<T: ?Sized> *mut T {
/// ///
/// unsafe { /// unsafe {
/// if let Some(val_back) = ptr.as_ref() { /// if let Some(val_back) = ptr.as_ref() {
/// println!("We got back the value: {}!", val_back); /// println!("We got back the value: {val_back}!");
/// } /// }
/// } /// }
/// ``` /// ```
@ -176,7 +176,7 @@ impl<T: ?Sized> *mut T {
/// ///
/// unsafe { /// unsafe {
/// let val_back = &*ptr; /// let val_back = &*ptr;
/// println!("We got back the value: {}!", val_back); /// println!("We got back the value: {val_back}!");
/// } /// }
/// ``` /// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")] #[stable(feature = "ptr_as_ref", since = "1.9.0")]
@ -409,7 +409,7 @@ impl<T: ?Sized> *mut T {
/// let first_value = unsafe { ptr.as_mut().unwrap() }; /// let first_value = unsafe { ptr.as_mut().unwrap() };
/// *first_value = 4; /// *first_value = 4;
/// # assert_eq!(s, [4, 2, 3]); /// # assert_eq!(s, [4, 2, 3]);
/// println!("{:?}", s); // It'll print: "[4, 2, 3]". /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
/// ``` /// ```
/// ///
/// # Null-unchecked version /// # Null-unchecked version
@ -424,7 +424,7 @@ impl<T: ?Sized> *mut T {
/// let first_value = unsafe { &mut *ptr }; /// let first_value = unsafe { &mut *ptr };
/// *first_value = 4; /// *first_value = 4;
/// # assert_eq!(s, [4, 2, 3]); /// # assert_eq!(s, [4, 2, 3]);
/// println!("{:?}", s); // It'll print: "[4, 2, 3]". /// println!("{s:?}"); // It'll print: "[4, 2, 3]".
/// ``` /// ```
#[stable(feature = "ptr_as_ref", since = "1.9.0")] #[stable(feature = "ptr_as_ref", since = "1.9.0")]
#[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")]

View file

@ -314,7 +314,7 @@ impl<T: ?Sized> NonNull<T> {
/// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!"); /// let ptr = NonNull::new(&mut x as *mut _).expect("ptr is null!");
/// ///
/// let ref_x = unsafe { ptr.as_ref() }; /// let ref_x = unsafe { ptr.as_ref() };
/// println!("{}", ref_x); /// println!("{ref_x}");
/// ``` /// ```
/// ///
/// [the module documentation]: crate::ptr#safety /// [the module documentation]: crate::ptr#safety

View file

@ -35,8 +35,8 @@
//! //!
//! let version = parse_version(&[1, 2, 3, 4]); //! let version = parse_version(&[1, 2, 3, 4]);
//! match version { //! match version {
//! Ok(v) => println!("working with version: {:?}", v), //! Ok(v) => println!("working with version: {v:?}"),
//! Err(e) => println!("error parsing header: {:?}", e), //! Err(e) => println!("error parsing header: {e:?}"),
//! } //! }
//! ``` //! ```
//! //!
@ -447,9 +447,9 @@
//! .collect(); //! .collect();
//! assert_eq!(errs.len(), 3); //! assert_eq!(errs.len(), 3);
//! assert_eq!(nums, [17, 99]); //! assert_eq!(nums, [17, 99]);
//! println!("results {:?}", results); //! println!("results {results:?}");
//! println!("errs {:?}", errs); //! println!("errs {errs:?}");
//! println!("nums {:?}", nums); //! println!("nums {nums:?}");
//! ``` //! ```
//! //!
//! ## Collecting into `Result` //! ## Collecting into `Result`
@ -756,7 +756,7 @@ impl<T, E> Result<T, E> {
/// ///
/// for num in line.lines() { /// for num in line.lines() {
/// match num.parse::<i32>().map(|i| i * 2) { /// match num.parse::<i32>().map(|i| i * 2) {
/// Ok(n) => println!("{}", n), /// Ok(n) => println!("{n}"),
/// Err(..) => {} /// Err(..) => {}
/// } /// }
/// } /// }
@ -838,7 +838,7 @@ impl<T, E> Result<T, E> {
/// Basic usage: /// Basic usage:
/// ///
/// ``` /// ```
/// fn stringify(x: u32) -> String { format!("error code: {}", x) } /// fn stringify(x: u32) -> String { format!("error code: {x}") }
/// ///
/// let x: Result<u32, u32> = Ok(2); /// let x: Result<u32, u32> = Ok(2);
/// assert_eq!(x.map_err(stringify), Ok(2)); /// assert_eq!(x.map_err(stringify), Ok(2));
@ -864,7 +864,7 @@ impl<T, E> Result<T, E> {
/// ///
/// let x: u8 = "4" /// let x: u8 = "4"
/// .parse::<u8>() /// .parse::<u8>()
/// .inspect(|x| println!("original: {}", x)) /// .inspect(|x| println!("original: {x}"))
/// .map(|x| x.pow(3)) /// .map(|x| x.pow(3))
/// .expect("failed to parse number"); /// .expect("failed to parse number");
/// ``` /// ```
@ -889,7 +889,7 @@ impl<T, E> Result<T, E> {
/// ///
/// fn read() -> io::Result<String> { /// fn read() -> io::Result<String> {
/// fs::read_to_string("address.txt") /// fs::read_to_string("address.txt")
/// .inspect_err(|e| eprintln!("failed to read file: {}", e)) /// .inspect_err(|e| eprintln!("failed to read file: {e}"))
/// } /// }
/// ``` /// ```
#[inline] #[inline]
@ -1198,7 +1198,7 @@ impl<T, E> Result<T, E> {
/// } /// }
/// ///
/// let s: String = only_good_news().into_ok(); /// let s: String = only_good_news().into_ok();
/// println!("{}", s); /// println!("{s}");
/// ``` /// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline] #[inline]
@ -1235,7 +1235,7 @@ impl<T, E> Result<T, E> {
/// } /// }
/// ///
/// let error: String = only_bad_news().into_err(); /// let error: String = only_bad_news().into_err();
/// println!("{}", error); /// println!("{error}");
/// ``` /// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline] #[inline]
@ -1781,7 +1781,7 @@ impl<T> Result<T, T> {
#[cold] #[cold]
#[track_caller] #[track_caller]
fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! { fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
panic!("{}: {:?}", msg, error) panic!("{msg}: {error:?}")
} }
// This is a separate function to avoid constructing a `dyn Debug` // This is a separate function to avoid constructing a `dyn Debug`

View file

@ -48,7 +48,7 @@ const fn slice_start_index_len_fail(index: usize, len: usize) -> ! {
// FIXME const-hack // FIXME const-hack
fn slice_start_index_len_fail_rt(index: usize, len: usize) -> ! { fn slice_start_index_len_fail_rt(index: usize, len: usize) -> ! {
panic!("range start index {} out of range for slice of length {}", index, len); panic!("range start index {index} out of range for slice of length {len}");
} }
const fn slice_start_index_len_fail_ct(_: usize, _: usize) -> ! { const fn slice_start_index_len_fail_ct(_: usize, _: usize) -> ! {
@ -69,7 +69,7 @@ const fn slice_end_index_len_fail(index: usize, len: usize) -> ! {
// FIXME const-hack // FIXME const-hack
fn slice_end_index_len_fail_rt(index: usize, len: usize) -> ! { fn slice_end_index_len_fail_rt(index: usize, len: usize) -> ! {
panic!("range end index {} out of range for slice of length {}", index, len); panic!("range end index {index} out of range for slice of length {len}");
} }
const fn slice_end_index_len_fail_ct(_: usize, _: usize) -> ! { const fn slice_end_index_len_fail_ct(_: usize, _: usize) -> ! {
@ -88,7 +88,7 @@ const fn slice_index_order_fail(index: usize, end: usize) -> ! {
// FIXME const-hack // FIXME const-hack
fn slice_index_order_fail_rt(index: usize, end: usize) -> ! { fn slice_index_order_fail_rt(index: usize, end: usize) -> ! {
panic!("slice index starts at {} but ends at {}", index, end); panic!("slice index starts at {index} but ends at {end}");
} }
const fn slice_index_order_fail_ct(_: usize, _: usize) -> ! { const fn slice_index_order_fail_ct(_: usize, _: usize) -> ! {

View file

@ -55,7 +55,7 @@ fn size_from_ptr<T>(_: *const T) -> usize {
/// ///
/// // Then, we iterate over it: /// // Then, we iterate over it:
/// for element in slice.iter() { /// for element in slice.iter() {
/// println!("{}", element); /// println!("{element}");
/// } /// }
/// ``` /// ```
/// ///
@ -176,7 +176,7 @@ impl<T> AsRef<[T]> for Iter<'_, T> {
/// } /// }
/// ///
/// // We now have "[2, 3, 4]": /// // We now have "[2, 3, 4]":
/// println!("{:?}", slice); /// println!("{slice:?}");
/// ``` /// ```
/// ///
/// [`iter_mut`]: slice::iter_mut /// [`iter_mut`]: slice::iter_mut
@ -266,7 +266,7 @@ impl<'a, T> IterMut<'a, T> {
/// *iter.next().unwrap() += 1; /// *iter.next().unwrap() += 1;
/// } /// }
/// // Now slice is "[2, 2, 3]": /// // Now slice is "[2, 2, 3]":
/// println!("{:?}", slice); /// println!("{slice:?}");
/// ``` /// ```
#[must_use = "`self` will be dropped if the result is not used"] #[must_use = "`self` will be dropped if the result is not used"]
#[stable(feature = "iter_to_slice", since = "1.4.0")] #[stable(feature = "iter_to_slice", since = "1.4.0")]

View file

@ -2012,7 +2012,7 @@ impl<T> [T] {
/// let v = [10, 40, 30, 20, 60, 50]; /// let v = [10, 40, 30, 20, 60, 50];
/// ///
/// for group in v.splitn(2, |num| *num % 3 == 0) { /// for group in v.splitn(2, |num| *num % 3 == 0) {
/// println!("{:?}", group); /// println!("{group:?}");
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -2067,7 +2067,7 @@ impl<T> [T] {
/// let v = [10, 40, 30, 20, 60, 50]; /// let v = [10, 40, 30, 20, 60, 50];
/// ///
/// for group in v.rsplitn(2, |num| *num % 3 == 0) { /// for group in v.rsplitn(2, |num| *num % 3 == 0) {
/// println!("{:?}", group); /// println!("{group:?}");
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]

View file

@ -104,7 +104,7 @@ fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
// 1. out of bounds // 1. out of bounds
if begin > s.len() || end > s.len() { if begin > s.len() || end > s.len() {
let oob_index = if begin > s.len() { begin } else { end }; let oob_index = if begin > s.len() { begin } else { end };
panic!("byte index {} is out of bounds of `{}`{}", oob_index, s_trunc, ellipsis); panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}");
} }
// 2. begin <= end // 2. begin <= end
@ -2446,7 +2446,7 @@ impl str {
/// ///
/// ``` /// ```
/// for c in "❤\n!".escape_debug() { /// for c in "❤\n!".escape_debug() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```
@ -2492,7 +2492,7 @@ impl str {
/// ///
/// ``` /// ```
/// for c in "❤\n!".escape_default() { /// for c in "❤\n!".escape_default() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```
@ -2530,7 +2530,7 @@ impl str {
/// ///
/// ``` /// ```
/// for c in "❤\n!".escape_unicode() { /// for c in "❤\n!".escape_unicode() {
/// print!("{}", c); /// print!("{c}");
/// } /// }
/// println!(); /// println!();
/// ``` /// ```

View file

@ -94,7 +94,7 @@
//! } //! }
//! //!
//! if let Err(panic) = thread.join() { //! if let Err(panic) = thread.join() {
//! println!("Thread had an error: {:?}", panic); //! println!("Thread had an error: {panic:?}");
//! } //! }
//! } //! }
//! ``` //! ```
@ -1345,7 +1345,7 @@ impl const From<bool> for AtomicBool {
/// ``` /// ```
/// use std::sync::atomic::AtomicBool; /// use std::sync::atomic::AtomicBool;
/// let atomic_bool = AtomicBool::from(true); /// let atomic_bool = AtomicBool::from(true);
/// assert_eq!(format!("{:?}", atomic_bool), "true") /// assert_eq!(format!("{atomic_bool:?}"), "true")
/// ``` /// ```
#[inline] #[inline]
fn from(b: bool) -> Self { fn from(b: bool) -> Self {

View file

@ -1214,7 +1214,7 @@ impl fmt::Debug for Duration {
/// use std::time::Duration; /// use std::time::Duration;
/// ///
/// if let Err(e) = Duration::try_from_secs_f32(-1.0) { /// if let Err(e) = Duration::try_from_secs_f32(-1.0) {
/// println!("Failed conversion to Duration: {}", e); /// println!("Failed conversion to Duration: {e}");
/// } /// }
/// ``` /// ```
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]

View file

@ -9,7 +9,7 @@ use crate::iter::FromIterator;
/// use std::io::*; /// use std::io::*;
/// let data = vec![1, 2, 3, 4, 5]; /// let data = vec![1, 2, 3, 4, 5];
/// let res: Result<()> = data.iter() /// let res: Result<()> = data.iter()
/// .map(|x| writeln!(stdout(), "{}", x)) /// .map(|x| writeln!(stdout(), "{x}"))
/// .collect(); /// .collect();
/// assert!(res.is_ok()); /// assert!(res.is_ok());
/// ``` /// ```

View file

@ -46,12 +46,12 @@ fn any_downcast_ref() {
match a.downcast_ref::<usize>() { match a.downcast_ref::<usize>() {
Some(&5) => {} Some(&5) => {}
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
match a.downcast_ref::<Test>() { match a.downcast_ref::<Test>() {
None => {} None => {}
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
} }
@ -69,7 +69,7 @@ fn any_downcast_mut() {
assert_eq!(*x, 5); assert_eq!(*x, 5);
*x = 612; *x = 612;
} }
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
match b_r.downcast_mut::<usize>() { match b_r.downcast_mut::<usize>() {
@ -77,27 +77,27 @@ fn any_downcast_mut() {
assert_eq!(*x, 7); assert_eq!(*x, 7);
*x = 413; *x = 413;
} }
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
match a_r.downcast_mut::<Test>() { match a_r.downcast_mut::<Test>() {
None => (), None => (),
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
match b_r.downcast_mut::<Test>() { match b_r.downcast_mut::<Test>() {
None => (), None => (),
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
match a_r.downcast_mut::<usize>() { match a_r.downcast_mut::<usize>() {
Some(&mut 612) => {} Some(&mut 612) => {}
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
match b_r.downcast_mut::<usize>() { match b_r.downcast_mut::<usize>() {
Some(&mut 413) => {} Some(&mut 413) => {}
x => panic!("Unexpected value {:?}", x), x => panic!("Unexpected value {x:?}"),
} }
} }

View file

@ -62,10 +62,10 @@ fn cell_update() {
#[test] #[test]
fn cell_has_sensible_show() { fn cell_has_sensible_show() {
let x = Cell::new("foo bar"); let x = Cell::new("foo bar");
assert!(format!("{:?}", x).contains(x.get())); assert!(format!("{x:?}").contains(x.get()));
x.set("baz qux"); x.set("baz qux");
assert!(format!("{:?}", x).contains(x.get())); assert!(format!("{x:?}").contains(x.get()));
} }
#[test] #[test]
@ -73,11 +73,11 @@ fn ref_and_refmut_have_sensible_show() {
let refcell = RefCell::new("foo"); let refcell = RefCell::new("foo");
let refcell_refmut = refcell.borrow_mut(); let refcell_refmut = refcell.borrow_mut();
assert!(format!("{:?}", refcell_refmut).contains("foo")); assert!(format!("{refcell_refmut:?}").contains("foo"));
drop(refcell_refmut); drop(refcell_refmut);
let refcell_ref = refcell.borrow(); let refcell_ref = refcell.borrow();
assert!(format!("{:?}", refcell_ref).contains("foo")); assert!(format!("{refcell_ref:?}").contains("foo"));
drop(refcell_ref); drop(refcell_ref);
} }

View file

@ -11,8 +11,8 @@ mod debug_struct {
} }
} }
assert_eq!("Foo", format!("{:?}", Foo)); assert_eq!("Foo", format!("{Foo:?}"));
assert_eq!("Foo", format!("{:#?}", Foo)); assert_eq!("Foo", format!("{Foo:#?}"));
} }
#[test] #[test]
@ -25,12 +25,12 @@ mod debug_struct {
} }
} }
assert_eq!("Foo { bar: true }", format!("{:?}", Foo)); assert_eq!("Foo { bar: true }", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"Foo { "Foo {
bar: true, bar: true,
}", }",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -47,13 +47,13 @@ mod debug_struct {
} }
} }
assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{:?}", Foo)); assert_eq!("Foo { bar: true, baz: 10/20 }", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"Foo { "Foo {
bar: true, bar: true,
baz: 10/20, baz: 10/20,
}", }",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -80,7 +80,7 @@ mod debug_struct {
assert_eq!( assert_eq!(
"Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }", "Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }",
format!("{:?}", Bar) format!("{Bar:?}")
); );
assert_eq!( assert_eq!(
"Bar { "Bar {
@ -90,7 +90,7 @@ mod debug_struct {
}, },
hello: \"world\", hello: \"world\",
}", }",
format!("{:#?}", Bar) format!("{Bar:#?}")
); );
} }
@ -104,8 +104,8 @@ mod debug_struct {
} }
} }
assert_eq!("Foo { .. }", format!("{:?}", Foo)); assert_eq!("Foo { .. }", format!("{Foo:?}"));
assert_eq!("Foo { .. }", format!("{:#?}", Foo)); assert_eq!("Foo { .. }", format!("{Foo:#?}"));
} }
#[test] #[test]
@ -121,14 +121,14 @@ mod debug_struct {
} }
} }
assert_eq!("Foo { bar: true, baz: 10/20, .. }", format!("{:?}", Foo)); assert_eq!("Foo { bar: true, baz: 10/20, .. }", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"Foo { "Foo {
bar: true, bar: true,
baz: 10/20, baz: 10/20,
.. ..
}", }",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -158,7 +158,7 @@ mod debug_struct {
assert_eq!( assert_eq!(
"Bar { foo: Foo { bar: true, baz: 10/20, .. }, hello: \"world\", .. }", "Bar { foo: Foo { bar: true, baz: 10/20, .. }, hello: \"world\", .. }",
format!("{:?}", Bar) format!("{Bar:?}")
); );
assert_eq!( assert_eq!(
"Bar { "Bar {
@ -170,7 +170,7 @@ mod debug_struct {
hello: \"world\", hello: \"world\",
.. ..
}", }",
format!("{:#?}", Bar) format!("{Bar:#?}")
); );
} }
} }
@ -188,8 +188,8 @@ mod debug_tuple {
} }
} }
assert_eq!("Foo", format!("{:?}", Foo)); assert_eq!("Foo", format!("{Foo:?}"));
assert_eq!("Foo", format!("{:#?}", Foo)); assert_eq!("Foo", format!("{Foo:#?}"));
} }
#[test] #[test]
@ -202,12 +202,12 @@ mod debug_tuple {
} }
} }
assert_eq!("Foo(true)", format!("{:?}", Foo)); assert_eq!("Foo(true)", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"Foo( "Foo(
true, true,
)", )",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -221,13 +221,13 @@ mod debug_tuple {
} }
} }
assert_eq!("Foo(true, 10/20)", format!("{:?}", Foo)); assert_eq!("Foo(true, 10/20)", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"Foo( "Foo(
true, true,
10/20, 10/20,
)", )",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -249,7 +249,7 @@ mod debug_tuple {
} }
} }
assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{:?}", Bar)); assert_eq!("Bar(Foo(true, 10/20), \"world\")", format!("{Bar:?}"));
assert_eq!( assert_eq!(
"Bar( "Bar(
Foo( Foo(
@ -258,7 +258,7 @@ mod debug_tuple {
), ),
\"world\", \"world\",
)", )",
format!("{:#?}", Bar) format!("{Bar:#?}")
); );
} }
} }
@ -276,8 +276,8 @@ mod debug_map {
} }
} }
assert_eq!("{}", format!("{:?}", Foo)); assert_eq!("{}", format!("{Foo:?}"));
assert_eq!("{}", format!("{:#?}", Foo)); assert_eq!("{}", format!("{Foo:#?}"));
} }
#[test] #[test]
@ -298,15 +298,15 @@ mod debug_map {
} }
} }
assert_eq!(format!("{:?}", Entry), format!("{:?}", KeyValue)); assert_eq!(format!("{Entry:?}"), format!("{KeyValue:?}"));
assert_eq!(format!("{:#?}", Entry), format!("{:#?}", KeyValue)); assert_eq!(format!("{Entry:#?}"), format!("{KeyValue:#?}"));
assert_eq!("{\"bar\": true}", format!("{:?}", Entry)); assert_eq!("{\"bar\": true}", format!("{Entry:?}"));
assert_eq!( assert_eq!(
"{ "{
\"bar\": true, \"bar\": true,
}", }",
format!("{:#?}", Entry) format!("{Entry:#?}")
); );
} }
@ -336,16 +336,16 @@ mod debug_map {
} }
} }
assert_eq!(format!("{:?}", Entry), format!("{:?}", KeyValue)); assert_eq!(format!("{Entry:?}"), format!("{KeyValue:?}"));
assert_eq!(format!("{:#?}", Entry), format!("{:#?}", KeyValue)); assert_eq!(format!("{Entry:#?}"), format!("{KeyValue:#?}"));
assert_eq!("{\"bar\": true, 10: 10/20}", format!("{:?}", Entry)); assert_eq!("{\"bar\": true, 10: 10/20}", format!("{Entry:?}"));
assert_eq!( assert_eq!(
"{ "{
\"bar\": true, \"bar\": true,
10: 10/20, 10: 10/20,
}", }",
format!("{:#?}", Entry) format!("{Entry:#?}")
); );
} }
@ -373,7 +373,7 @@ mod debug_map {
assert_eq!( assert_eq!(
"{\"foo\": {\"bar\": true, 10: 10/20}, \ "{\"foo\": {\"bar\": true, 10: 10/20}, \
{\"bar\": true, 10: 10/20}: \"world\"}", {\"bar\": true, 10: 10/20}: \"world\"}",
format!("{:?}", Bar) format!("{Bar:?}")
); );
assert_eq!( assert_eq!(
"{ "{
@ -386,7 +386,7 @@ mod debug_map {
10: 10/20, 10: 10/20,
}: \"world\", }: \"world\",
}", }",
format!("{:#?}", Bar) format!("{Bar:#?}")
); );
} }
@ -441,7 +441,7 @@ mod debug_map {
} }
} }
format!("{:?}", Foo); format!("{Foo:?}");
} }
#[test] #[test]
@ -455,7 +455,7 @@ mod debug_map {
} }
} }
format!("{:?}", Foo); format!("{Foo:?}");
} }
#[test] #[test]
@ -469,7 +469,7 @@ mod debug_map {
} }
} }
format!("{:?}", Foo); format!("{Foo:?}");
} }
} }
@ -486,8 +486,8 @@ mod debug_set {
} }
} }
assert_eq!("{}", format!("{:?}", Foo)); assert_eq!("{}", format!("{Foo:?}"));
assert_eq!("{}", format!("{:#?}", Foo)); assert_eq!("{}", format!("{Foo:#?}"));
} }
#[test] #[test]
@ -500,12 +500,12 @@ mod debug_set {
} }
} }
assert_eq!("{true}", format!("{:?}", Foo)); assert_eq!("{true}", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"{ "{
true, true,
}", }",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -519,13 +519,13 @@ mod debug_set {
} }
} }
assert_eq!("{true, 10/20}", format!("{:?}", Foo)); assert_eq!("{true, 10/20}", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"{ "{
true, true,
10/20, 10/20,
}", }",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -547,7 +547,7 @@ mod debug_set {
} }
} }
assert_eq!("{{true, 10/20}, \"world\"}", format!("{:?}", Bar)); assert_eq!("{{true, 10/20}, \"world\"}", format!("{Bar:?}"));
assert_eq!( assert_eq!(
"{ "{
{ {
@ -556,7 +556,7 @@ mod debug_set {
}, },
\"world\", \"world\",
}", }",
format!("{:#?}", Bar) format!("{Bar:#?}")
); );
} }
} }
@ -574,8 +574,8 @@ mod debug_list {
} }
} }
assert_eq!("[]", format!("{:?}", Foo)); assert_eq!("[]", format!("{Foo:?}"));
assert_eq!("[]", format!("{:#?}", Foo)); assert_eq!("[]", format!("{Foo:#?}"));
} }
#[test] #[test]
@ -588,12 +588,12 @@ mod debug_list {
} }
} }
assert_eq!("[true]", format!("{:?}", Foo)); assert_eq!("[true]", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"[ "[
true, true,
]", ]",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -607,13 +607,13 @@ mod debug_list {
} }
} }
assert_eq!("[true, 10/20]", format!("{:?}", Foo)); assert_eq!("[true, 10/20]", format!("{Foo:?}"));
assert_eq!( assert_eq!(
"[ "[
true, true,
10/20, 10/20,
]", ]",
format!("{:#?}", Foo) format!("{Foo:#?}")
); );
} }
@ -635,7 +635,7 @@ mod debug_list {
} }
} }
assert_eq!("[[true, 10/20], \"world\"]", format!("{:?}", Bar)); assert_eq!("[[true, 10/20], \"world\"]", format!("{Bar:?}"));
assert_eq!( assert_eq!(
"[ "[
[ [
@ -644,7 +644,7 @@ mod debug_list {
], ],
\"world\", \"world\",
]", ]",
format!("{:#?}", Bar) format!("{Bar:#?}")
); );
} }
} }
@ -668,13 +668,13 @@ fn test_formatting_parameters_are_forwarded() {
set.insert(1024); set.insert(1024);
set.insert(7); set.insert(7);
assert_eq!(format!("{:03?}", struct_), "Foo { bar: 1024, baz: 007 }"); assert_eq!(format!("{struct_:03?}"), "Foo { bar: 1024, baz: 007 }");
assert_eq!(format!("{:03?}", tuple), "(1024, 007)"); assert_eq!(format!("{tuple:03?}"), "(1024, 007)");
assert_eq!(format!("{:03?}", list), "[1024, 007]"); assert_eq!(format!("{list:03?}"), "[1024, 007]");
assert_eq!(format!("{:03?}", map), r#"{"bar": 1024, "baz": 007}"#); assert_eq!(format!("{map:03?}"), r#"{"bar": 1024, "baz": 007}"#);
assert_eq!(format!("{:03?}", set), "{007, 1024}"); assert_eq!(format!("{set:03?}"), "{007, 1024}");
assert_eq!( assert_eq!(
format!("{:#03?}", struct_), format!("{struct_:#03?}"),
" "
Foo { Foo {
bar: 1024, bar: 1024,
@ -684,7 +684,7 @@ Foo {
.trim() .trim()
); );
assert_eq!( assert_eq!(
format!("{:#03?}", tuple), format!("{tuple:#03?}"),
" "
( (
1024, 1024,
@ -694,7 +694,7 @@ Foo {
.trim() .trim()
); );
assert_eq!( assert_eq!(
format!("{:#03?}", list), format!("{list:#03?}"),
" "
[ [
1024, 1024,
@ -704,7 +704,7 @@ Foo {
.trim() .trim()
); );
assert_eq!( assert_eq!(
format!("{:#03?}", map), format!("{map:#03?}"),
r#" r#"
{ {
"bar": 1024, "bar": 1024,
@ -714,7 +714,7 @@ Foo {
.trim() .trim()
); );
assert_eq!( assert_eq!(
format!("{:#03?}", set), format!("{set:#03?}"),
" "
{ {
007, 007,

View file

@ -6,7 +6,7 @@ mod num;
fn test_format_flags() { fn test_format_flags() {
// No residual flags left by pointer formatting // No residual flags left by pointer formatting
let p = "".as_ptr(); let p = "".as_ptr();
assert_eq!(format!("{:p} {:x}", p, 16), format!("{:p} 10", p)); assert_eq!(format!("{:p} {:x}", p, 16), format!("{p:p} 10"));
assert_eq!(format!("{: >3}", 'a'), " a"); assert_eq!(format!("{: >3}", 'a'), " a");
} }
@ -15,8 +15,8 @@ fn test_format_flags() {
fn test_pointer_formats_data_pointer() { fn test_pointer_formats_data_pointer() {
let b: &[u8] = b""; let b: &[u8] = b"";
let s: &str = ""; let s: &str = "";
assert_eq!(format!("{:p}", s), format!("{:p}", s.as_ptr())); assert_eq!(format!("{s:p}"), format!("{:p}", s.as_ptr()));
assert_eq!(format!("{:p}", b), format!("{:p}", b.as_ptr())); assert_eq!(format!("{b:p}"), format!("{:p}", b.as_ptr()));
} }
#[test] #[test]
@ -41,5 +41,5 @@ fn pad_integral_resets() {
} }
} }
assert_eq!(format!("{:<03}", Bar), "1 0051 "); assert_eq!(format!("{Bar:<03}"), "1 0051 ");
} }

View file

@ -126,7 +126,7 @@ fn test_format_int_exp_limits() {
fn test_format_int_exp_precision() { fn test_format_int_exp_precision() {
//test that float and integer match //test that float and integer match
let big_int: u32 = 314_159_265; let big_int: u32 = 314_159_265;
assert_eq!(format!("{:.1e}", big_int), format!("{:.1e}", f64::from(big_int))); assert_eq!(format!("{big_int:.1e}"), format!("{:.1e}", f64::from(big_int)));
//test adding precision //test adding precision
assert_eq!(format!("{:.10e}", i8::MIN), "-1.2800000000e2"); assert_eq!(format!("{:.10e}", i8::MIN), "-1.2800000000e2");

View file

@ -113,7 +113,7 @@ fn aliasing_in_get() {
x.set(42).unwrap(); x.set(42).unwrap();
let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+ let at_x = x.get().unwrap(); // --- (shared) borrow of inner `Option<T>` --+
let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` | let _ = x.set(27); // <-- temporary (unique) borrow of inner `Option<T>` |
println!("{}", at_x); // <------- up until here ---------------------------+ println!("{at_x}"); // <------- up until here ---------------------------+
} }
#[test] #[test]

View file

@ -15,7 +15,7 @@ macro_rules! test_literal {
for input in inputs { for input in inputs {
assert_eq!(input.parse(), Ok(x64)); assert_eq!(input.parse(), Ok(x64));
assert_eq!(input.parse(), Ok(x32)); assert_eq!(input.parse(), Ok(x32));
let neg_input = &format!("-{}", input); let neg_input = &format!("-{input}");
assert_eq!(neg_input.parse(), Ok(-x64)); assert_eq!(neg_input.parse(), Ok(-x64));
assert_eq!(neg_input.parse(), Ok(-x32)); assert_eq!(neg_input.parse(), Ok(-x32));
} }
@ -123,9 +123,9 @@ fn inf() {
#[test] #[test]
fn massive_exponent() { fn massive_exponent() {
let max = i64::MAX; let max = i64::MAX;
assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY)); assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e-{}000", max).parse(), Ok(0.0)); assert_eq!(format!("1e-{max}000").parse(), Ok(0.0));
assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY)); assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY));
} }
#[test] #[test]

View file

@ -46,7 +46,7 @@ fn valid() {
assert_eq!(parse_positive(b".1e300"), Some(new_number(299, 1))); assert_eq!(parse_positive(b".1e300"), Some(new_number(299, 1)));
assert_eq!(parse_positive(b"101e-33"), Some(new_number(-33, 101))); assert_eq!(parse_positive(b"101e-33"), Some(new_number(-33, 101)));
let zeros = "0".repeat(25); let zeros = "0".repeat(25);
let s = format!("1.5e{}", zeros); let s = format!("1.5e{zeros}");
assert_eq!(parse_positive(s.as_bytes()), Some(new_number(-1, 15))); assert_eq!(parse_positive(s.as_bytes()), Some(new_number(-1, 15)));
} }

View file

@ -20,7 +20,7 @@ mod random;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded { pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 { match decode(v).1 {
FullDecoded::Finite(decoded) => decoded, FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded), full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
} }
} }

View file

@ -15,7 +15,7 @@ use rand::SeedableRng;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded { pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 { match decode(v).1 {
FullDecoded::Finite(decoded) => decoded, FullDecoded::Finite(decoded) => decoded,
full_decoded => panic!("expected finite, got {:?} instead", full_decoded), full_decoded => panic!("expected finite, got {full_decoded:?} instead"),
} }
} }

View file

@ -550,7 +550,7 @@ fn dyn_metadata() {
assert_eq!(meta.align_of(), std::mem::align_of::<Something>()); assert_eq!(meta.align_of(), std::mem::align_of::<Something>());
assert_eq!(meta.layout(), std::alloc::Layout::new::<Something>()); assert_eq!(meta.layout(), std::alloc::Layout::new::<Something>());
assert!(format!("{:?}", meta).starts_with("DynMetadata(0x")); assert!(format!("{meta:?}").starts_with("DynMetadata(0x"));
} }
#[test] #[test]

View file

@ -80,9 +80,9 @@ fn test_fmt_default() {
let ok: Result<isize, &'static str> = Ok(100); let ok: Result<isize, &'static str> = Ok(100);
let err: Result<isize, &'static str> = Err("Err"); let err: Result<isize, &'static str> = Err("Err");
let s = format!("{:?}", ok); let s = format!("{ok:?}");
assert_eq!(s, "Ok(100)"); assert_eq!(s, "Ok(100)");
let s = format!("{:?}", err); let s = format!("{err:?}");
assert_eq!(s, "Err(\"Err\")"); assert_eq!(s, "Err(\"Err\")");
} }

View file

@ -187,7 +187,7 @@ mod tests {
fn main() { fn main() {
{ {
let (energy_before, energy_after) = nbody::run(1000); let (energy_before, energy_after) = nbody::run(1000);
println!("Energy before: {}", energy_before); println!("Energy before: {energy_before}");
println!("Energy after: {}", energy_after); println!("Energy after: {energy_after}");
} }
} }

View file

@ -1106,7 +1106,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")] #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f32_unsuffixed(n: f32) -> Literal { pub fn f32_unsuffixed(n: f32) -> Literal {
if !n.is_finite() { if !n.is_finite() {
panic!("Invalid float literal {}", n); panic!("Invalid float literal {n}");
} }
let mut repr = n.to_string(); let mut repr = n.to_string();
if !repr.contains('.') { if !repr.contains('.') {
@ -1131,7 +1131,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")] #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f32_suffixed(n: f32) -> Literal { pub fn f32_suffixed(n: f32) -> Literal {
if !n.is_finite() { if !n.is_finite() {
panic!("Invalid float literal {}", n); panic!("Invalid float literal {n}");
} }
Literal(bridge::client::Literal::f32(&n.to_string())) Literal(bridge::client::Literal::f32(&n.to_string()))
} }
@ -1151,7 +1151,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")] #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f64_unsuffixed(n: f64) -> Literal { pub fn f64_unsuffixed(n: f64) -> Literal {
if !n.is_finite() { if !n.is_finite() {
panic!("Invalid float literal {}", n); panic!("Invalid float literal {n}");
} }
let mut repr = n.to_string(); let mut repr = n.to_string();
if !repr.contains('.') { if !repr.contains('.') {
@ -1176,7 +1176,7 @@ impl Literal {
#[stable(feature = "proc_macro_lib2", since = "1.29.0")] #[stable(feature = "proc_macro_lib2", since = "1.29.0")]
pub fn f64_suffixed(n: f64) -> Literal { pub fn f64_suffixed(n: f64) -> Literal {
if !n.is_finite() { if !n.is_finite() {
panic!("Invalid float literal {}", n); panic!("Invalid float literal {n}");
} }
Literal(bridge::client::Literal::f64(&n.to_string())) Literal(bridge::client::Literal::f64(&n.to_string()))
} }

View file

@ -83,7 +83,7 @@ pub use alloc_crate::alloc::*;
/// ///
/// fn main() { /// fn main() {
/// let a = Box::new(4); // Allocates from the system allocator. /// let a = Box::new(4); // Allocates from the system allocator.
/// println!("{}", a); /// println!("{a}");
/// } /// }
/// ``` /// ```
/// ///

View file

@ -57,10 +57,10 @@ fn test_debug() {
\n { fn: \"std::rt::lang_start\", file: \"rust/rt.rs\", line: 400 },\ \n { fn: \"std::rt::lang_start\", file: \"rust/rt.rs\", line: 400 },\
\n]"; \n]";
assert_eq!(format!("{:#?}", backtrace), expected); assert_eq!(format!("{backtrace:#?}"), expected);
// Format the backtrace a second time, just to make sure lazily resolved state is stable // Format the backtrace a second time, just to make sure lazily resolved state is stable
assert_eq!(format!("{:#?}", backtrace), expected); assert_eq!(format!("{backtrace:#?}"), expected);
} }
#[test] #[test]
@ -91,5 +91,5 @@ fn test_frames() {
let mut iter = frames.iter().zip(expected.iter()); let mut iter = frames.iter().zip(expected.iter());
assert!(iter.all(|(f, e)| format!("{:#?}", f) == *e)); assert!(iter.all(|(f, e)| format!("{f:#?}") == *e));
} }

View file

@ -109,8 +109,8 @@ use crate::sys;
/// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; /// let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"];
/// for &book in &to_find { /// for &book in &to_find {
/// match book_reviews.get(book) { /// match book_reviews.get(book) {
/// Some(review) => println!("{}: {}", book, review), /// Some(review) => println!("{book}: {review}"),
/// None => println!("{} is unreviewed.", book) /// None => println!("{book} is unreviewed.")
/// } /// }
/// } /// }
/// ///
@ -119,7 +119,7 @@ use crate::sys;
/// ///
/// // Iterate over everything. /// // Iterate over everything.
/// for (book, review) in &book_reviews { /// for (book, review) in &book_reviews {
/// println!("{}: \"{}\"", book, review); /// println!("{book}: \"{review}\"");
/// } /// }
/// ``` /// ```
/// ///
@ -199,7 +199,7 @@ use crate::sys;
/// ///
/// // Use derived implementation to print the status of the vikings. /// // Use derived implementation to print the status of the vikings.
/// for (viking, health) in &vikings { /// for (viking, health) in &vikings {
/// println!("{:?} has {} hp", viking, health); /// println!("{viking:?} has {health} hp");
/// } /// }
/// ``` /// ```
@ -341,7 +341,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]); /// ]);
/// ///
/// for key in map.keys() { /// for key in map.keys() {
/// println!("{}", key); /// println!("{key}");
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -392,7 +392,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]); /// ]);
/// ///
/// for val in map.values() { /// for val in map.values() {
/// println!("{}", val); /// println!("{val}");
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -419,7 +419,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// } /// }
/// ///
/// for val in map.values() { /// for val in map.values() {
/// println!("{}", val); /// println!("{val}");
/// } /// }
/// ``` /// ```
#[stable(feature = "map_values_mut", since = "1.10.0")] #[stable(feature = "map_values_mut", since = "1.10.0")]
@ -470,7 +470,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]); /// ]);
/// ///
/// for (key, val) in map.iter() { /// for (key, val) in map.iter() {
/// println!("key: {} val: {}", key, val); /// println!("key: {key} val: {val}");
/// } /// }
/// ``` /// ```
#[rustc_lint_query_instability] #[rustc_lint_query_instability]
@ -500,7 +500,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// } /// }
/// ///
/// for (key, val) in &map { /// for (key, val) in &map {
/// println!("key: {} val: {}", key, val); /// println!("key: {key} val: {val}");
/// } /// }
/// ``` /// ```
#[rustc_lint_query_instability] #[rustc_lint_query_instability]

View file

@ -515,10 +515,10 @@ fn test_show() {
map.insert(1, 2); map.insert(1, 2);
map.insert(3, 4); map.insert(3, 4);
let map_str = format!("{:?}", map); let map_str = format!("{map:?}");
assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
assert_eq!(format!("{:?}", empty), "{}"); assert_eq!(format!("{empty:?}"), "{}");
} }
#[test] #[test]
@ -702,7 +702,7 @@ fn test_entry_take_doesnt_corrupt() {
// Test for #19292 // Test for #19292
fn check(m: &HashMap<i32, ()>) { fn check(m: &HashMap<i32, ()>) {
for k in m.keys() { for k in m.keys() {
assert!(m.contains_key(k), "{} is in keys() but not in the map?", k); assert!(m.contains_key(k), "{k} is in keys() but not in the map?");
} }
} }

View file

@ -66,7 +66,7 @@ use super::map::{map_try_reserve_error, RandomState};
/// ///
/// // Iterate over everything. /// // Iterate over everything.
/// for book in &books { /// for book in &books {
/// println!("{}", book); /// println!("{book}");
/// } /// }
/// ``` /// ```
/// ///
@ -91,7 +91,7 @@ use super::map::{map_try_reserve_error, RandomState};
/// ///
/// // Use derived implementation to print the vikings. /// // Use derived implementation to print the vikings.
/// for x in &vikings { /// for x in &vikings {
/// println!("{:?}", x); /// println!("{x:?}");
/// } /// }
/// ``` /// ```
/// ///
@ -181,7 +181,7 @@ impl<T, S> HashSet<T, S> {
/// ///
/// // Will print in an arbitrary order. /// // Will print in an arbitrary order.
/// for x in set.iter() { /// for x in set.iter() {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
#[inline] #[inline]
@ -244,7 +244,7 @@ impl<T, S> HashSet<T, S> {
/// ///
/// // print 1, 2, 3 in an arbitrary order /// // print 1, 2, 3 in an arbitrary order
/// for i in set.drain() { /// for i in set.drain() {
/// println!("{}", i); /// println!("{i}");
/// } /// }
/// ///
/// assert!(set.is_empty()); /// assert!(set.is_empty());
@ -525,7 +525,7 @@ where
/// ///
/// // Can be seen as `a - b`. /// // Can be seen as `a - b`.
/// for x in a.difference(&b) { /// for x in a.difference(&b) {
/// println!("{}", x); // Print 1 /// println!("{x}"); // Print 1
/// } /// }
/// ///
/// let diff: HashSet<_> = a.difference(&b).collect(); /// let diff: HashSet<_> = a.difference(&b).collect();
@ -555,7 +555,7 @@ where
/// ///
/// // Print 1, 4 in arbitrary order. /// // Print 1, 4 in arbitrary order.
/// for x in a.symmetric_difference(&b) { /// for x in a.symmetric_difference(&b) {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// let diff1: HashSet<_> = a.symmetric_difference(&b).collect(); /// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
@ -586,7 +586,7 @@ where
/// ///
/// // Print 2, 3 in arbitrary order. /// // Print 2, 3 in arbitrary order.
/// for x in a.intersection(&b) { /// for x in a.intersection(&b) {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// let intersection: HashSet<_> = a.intersection(&b).collect(); /// let intersection: HashSet<_> = a.intersection(&b).collect();
@ -615,7 +615,7 @@ where
/// ///
/// // Print 1, 2, 3, 4 in arbitrary order. /// // Print 1, 2, 3, 4 in arbitrary order.
/// for x in a.union(&b) { /// for x in a.union(&b) {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ///
/// let union: HashSet<_> = a.union(&b).collect(); /// let union: HashSet<_> = a.union(&b).collect();
@ -1451,7 +1451,7 @@ impl<T, S> IntoIterator for HashSet<T, S> {
/// ///
/// // Will print in an arbitrary order. /// // Will print in an arbitrary order.
/// for x in &v { /// for x in &v {
/// println!("{}", x); /// println!("{x}");
/// } /// }
/// ``` /// ```
#[inline] #[inline]

View file

@ -301,10 +301,10 @@ fn test_show() {
set.insert(1); set.insert(1);
set.insert(2); set.insert(2);
let set_str = format!("{:?}", set); let set_str = format!("{set:?}");
assert!(set_str == "{1, 2}" || set_str == "{2, 1}"); assert!(set_str == "{1, 2}" || set_str == "{2, 1}");
assert_eq!(format!("{:?}", empty), "{}"); assert_eq!(format!("{empty:?}"), "{}");
} }
#[test] #[test]

View file

@ -199,7 +199,7 @@
//! ``` //! ```
//! let vec = vec![1, 2, 3, 4]; //! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter() { //! for x in vec.iter() {
//! println!("vec contained {}", x); //! println!("vec contained {x:?}");
//! } //! }
//! ``` //! ```
//! //!
@ -246,7 +246,7 @@
//! ``` //! ```
//! let vec = vec![1, 2, 3, 4]; //! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter().rev() { //! for x in vec.iter().rev() {
//! println!("vec contained {}", x); //! println!("vec contained {x:?}");
//! } //! }
//! ``` //! ```
//! //!
@ -306,7 +306,7 @@
//! //!
//! println!("Number of occurrences of each character"); //! println!("Number of occurrences of each character");
//! for (char, count) in &count { //! for (char, count) in &count {
//! println!("{}: {}", char, count); //! println!("{char}: {count}");
//! } //! }
//! ``` //! ```
//! //!
@ -339,7 +339,7 @@
//! // Check if they're sober enough to have another beer. //! // Check if they're sober enough to have another beer.
//! if person.blood_alcohol > 0.3 { //! if person.blood_alcohol > 0.3 {
//! // Too drunk... for now. //! // Too drunk... for now.
//! println!("Sorry {}, I have to cut you off", id); //! println!("Sorry {id}, I have to cut you off");
//! } else { //! } else {
//! // Have another! //! // Have another!
//! person.blood_alcohol += 0.1; //! person.blood_alcohol += 0.1;

View file

@ -118,7 +118,7 @@ pub struct VarsOs {
/// // We will iterate through the references to the element returned by /// // We will iterate through the references to the element returned by
/// // env::vars(); /// // env::vars();
/// for (key, value) in env::vars() { /// for (key, value) in env::vars() {
/// println!("{}: {}", key, value); /// println!("{key}: {value}");
/// } /// }
/// ``` /// ```
/// ///
@ -148,7 +148,7 @@ pub fn vars() -> Vars {
/// // We will iterate through the references to the element returned by /// // We will iterate through the references to the element returned by
/// // env::vars_os(); /// // env::vars_os();
/// for (key, value) in env::vars_os() { /// for (key, value) in env::vars_os() {
/// println!("{:?}: {:?}", key, value); /// println!("{key:?}: {value:?}");
/// } /// }
/// ``` /// ```
#[must_use] #[must_use]
@ -212,8 +212,8 @@ impl fmt::Debug for VarsOs {
/// ///
/// let key = "HOME"; /// let key = "HOME";
/// match env::var(key) { /// match env::var(key) {
/// Ok(val) => println!("{}: {:?}", key, val), /// Ok(val) => println!("{key}: {val:?}"),
/// Err(e) => println!("couldn't interpret {}: {}", key, e), /// Err(e) => println!("couldn't interpret {key}: {e}"),
/// } /// }
/// ``` /// ```
#[stable(feature = "env", since = "1.0.0")] #[stable(feature = "env", since = "1.0.0")]
@ -252,8 +252,8 @@ fn _var(key: &OsStr) -> Result<String, VarError> {
/// ///
/// let key = "HOME"; /// let key = "HOME";
/// match env::var_os(key) { /// match env::var_os(key) {
/// Some(val) => println!("{}: {:?}", key, val), /// Some(val) => println!("{key}: {val:?}"),
/// None => println!("{} is not defined in the environment.", key) /// None => println!("{key} is not defined in the environment.")
/// } /// }
/// ``` /// ```
#[must_use] #[must_use]
@ -343,7 +343,7 @@ pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) {
fn _set_var(key: &OsStr, value: &OsStr) { fn _set_var(key: &OsStr, value: &OsStr) {
os_imp::setenv(key, value).unwrap_or_else(|e| { os_imp::setenv(key, value).unwrap_or_else(|e| {
panic!("failed to set environment variable `{:?}` to `{:?}`: {}", key, value, e) panic!("failed to set environment variable `{key:?}` to `{value:?}`: {e}")
}) })
} }
@ -385,7 +385,7 @@ pub fn remove_var<K: AsRef<OsStr>>(key: K) {
fn _remove_var(key: &OsStr) { fn _remove_var(key: &OsStr) {
os_imp::unsetenv(key) os_imp::unsetenv(key)
.unwrap_or_else(|e| panic!("failed to remove environment variable `{:?}`: {}", key, e)) .unwrap_or_else(|e| panic!("failed to remove environment variable `{key:?}`: {e}"))
} }
/// An iterator that splits an environment variable into paths according to /// An iterator that splits an environment variable into paths according to
@ -421,7 +421,7 @@ pub struct SplitPaths<'a> {
/// println!("'{}'", path.display()); /// println!("'{}'", path.display());
/// } /// }
/// } /// }
/// None => println!("{} is not defined in the environment.", key) /// None => println!("{key} is not defined in the environment.")
/// } /// }
/// ``` /// ```
#[stable(feature = "env", since = "1.0.0")] #[stable(feature = "env", since = "1.0.0")]
@ -684,7 +684,7 @@ pub fn temp_dir() -> PathBuf {
/// match env::current_exe() { /// match env::current_exe() {
/// Ok(exe_path) => println!("Path of this executable is: {}", /// Ok(exe_path) => println!("Path of this executable is: {}",
/// exe_path.display()), /// exe_path.display()),
/// Err(e) => println!("failed to get current exe path: {}", e), /// Err(e) => println!("failed to get current exe path: {e}"),
/// }; /// };
/// ``` /// ```
#[stable(feature = "env", since = "1.0.0")] #[stable(feature = "env", since = "1.0.0")]
@ -755,7 +755,7 @@ pub struct ArgsOs {
/// ///
/// // Prints each argument on a separate line /// // Prints each argument on a separate line
/// for argument in env::args() { /// for argument in env::args() {
/// println!("{}", argument); /// println!("{argument}");
/// } /// }
/// ``` /// ```
#[stable(feature = "env", since = "1.0.0")] #[stable(feature = "env", since = "1.0.0")]
@ -790,7 +790,7 @@ pub fn args() -> Args {
/// ///
/// // Prints each argument on a separate line /// // Prints each argument on a separate line
/// for argument in env::args_os() { /// for argument in env::args_os() {
/// println!("{:?}", argument); /// println!("{argument:?}");
/// } /// }
/// ``` /// ```
#[stable(feature = "env", since = "1.0.0")] #[stable(feature = "env", since = "1.0.0")]

View file

@ -96,7 +96,7 @@ pub trait Error: Debug + Display {
/// fn main() { /// fn main() {
/// match get_super_error() { /// match get_super_error() {
/// Err(e) => { /// Err(e) => {
/// println!("Error: {}", e); /// println!("Error: {e}");
/// println!("Caused by: {}", e.source().unwrap()); /// println!("Caused by: {}", e.source().unwrap());
/// } /// }
/// _ => println!("No error"), /// _ => println!("No error"),
@ -139,7 +139,7 @@ pub trait Error: Debug + Display {
/// ``` /// ```
/// if let Err(e) = "xc".parse::<u32>() { /// if let Err(e) = "xc".parse::<u32>() {
/// // Print `e` itself, no need for description(). /// // Print `e` itself, no need for description().
/// eprintln!("Error: {}", e); /// eprintln!("Error: {e}");
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -1074,7 +1074,7 @@ impl<E> Report<E> {
/// ///
/// let error = SuperError { source: SuperErrorSideKick }; /// let error = SuperError { source: SuperErrorSideKick };
/// let report = Report::new(error).pretty(true); /// let report = Report::new(error).pretty(true);
/// eprintln!("Error: {:?}", report); /// eprintln!("Error: {report:?}");
/// ``` /// ```
/// ///
/// This example produces the following output: /// This example produces the following output:
@ -1135,7 +1135,7 @@ impl<E> Report<E> {
/// let source = SuperErrorSideKick { source }; /// let source = SuperErrorSideKick { source };
/// let error = SuperError { source }; /// let error = SuperError { source };
/// let report = Report::new(error).pretty(true); /// let report = Report::new(error).pretty(true);
/// eprintln!("Error: {:?}", report); /// eprintln!("Error: {report:?}");
/// ``` /// ```
/// ///
/// This example produces the following output: /// This example produces the following output:
@ -1210,7 +1210,7 @@ impl<E> Report<E> {
/// let source = SuperErrorSideKick::new(); /// let source = SuperErrorSideKick::new();
/// let error = SuperError { source }; /// let error = SuperError { source };
/// let report = Report::new(error).pretty(true).show_backtrace(true); /// let report = Report::new(error).pretty(true).show_backtrace(true);
/// eprintln!("Error: {:?}", report); /// eprintln!("Error: {report:?}");
/// ``` /// ```
/// ///
/// This example produces something similar to the following output: /// This example produces something similar to the following output:
@ -1267,7 +1267,7 @@ where
let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain); let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
for cause in sources { for cause in sources {
write!(f, ": {}", cause)?; write!(f, ": {cause}")?;
} }
Ok(()) Ok(())
@ -1278,7 +1278,7 @@ where
fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let error = &self.error; let error = &self.error;
write!(f, "{}", error)?; write!(f, "{error}")?;
if let Some(cause) = error.source() { if let Some(cause) = error.source() {
write!(f, "\n\nCaused by:")?; write!(f, "\n\nCaused by:")?;
@ -1289,9 +1289,9 @@ where
writeln!(f)?; writeln!(f)?;
let mut indented = Indented { inner: f }; let mut indented = Indented { inner: f };
if multiple { if multiple {
write!(indented, "{: >4}: {}", ind, error)?; write!(indented, "{ind: >4}: {error}")?;
} else { } else {
write!(indented, " {}", error)?; write!(indented, " {error}")?;
} }
} }
} }
@ -1333,7 +1333,7 @@ impl Report<Box<dyn Error>> {
let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain); let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
for cause in sources { for cause in sources {
write!(f, ": {}", cause)?; write!(f, ": {cause}")?;
} }
Ok(()) Ok(())
@ -1344,7 +1344,7 @@ impl Report<Box<dyn Error>> {
fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let error = &self.error; let error = &self.error;
write!(f, "{}", error)?; write!(f, "{error}")?;
if let Some(cause) = error.source() { if let Some(cause) = error.source() {
write!(f, "\n\nCaused by:")?; write!(f, "\n\nCaused by:")?;
@ -1355,9 +1355,9 @@ impl Report<Box<dyn Error>> {
writeln!(f)?; writeln!(f)?;
let mut indented = Indented { inner: f }; let mut indented = Indented { inner: f };
if multiple { if multiple {
write!(indented, "{: >4}: {}", ind, error)?; write!(indented, "{ind: >4}: {error}")?;
} else { } else {
write!(indented, " {}", error)?; write!(indented, " {error}")?;
} }
} }
} }

View file

@ -130,7 +130,7 @@ Stack backtrace:
error.backtrace = Some(trace); error.backtrace = Some(trace);
let report = Report::new(error).pretty(true).show_backtrace(true); let report = Report::new(error).pretty(true).show_backtrace(true);
println!("Error: {}", report); println!("Error: {report}");
assert_eq!(expected.trim_end(), report.to_string()); assert_eq!(expected.trim_end(), report.to_string());
} }
@ -155,7 +155,7 @@ Stack backtrace:
let error = GenericError::new_with_source("Error with two sources", error); let error = GenericError::new_with_source("Error with two sources", error);
let report = Report::new(error).pretty(true).show_backtrace(true); let report = Report::new(error).pretty(true).show_backtrace(true);
println!("Error: {}", report); println!("Error: {report}");
assert_eq!(expected.trim_end(), report.to_string()); assert_eq!(expected.trim_end(), report.to_string());
} }
@ -355,7 +355,7 @@ Caused by:
1: The message goes on and on."; 1: The message goes on and on.";
let actual = report.to_string(); let actual = report.to_string();
println!("{}", actual); println!("{actual}");
assert_eq!(expected, actual); assert_eq!(expected, actual);
} }

View file

@ -1120,7 +1120,7 @@ impl fmt::Display for FromBytesWithNulError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.description())?; f.write_str(self.description())?;
if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind { if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
write!(f, " at byte pos {}", pos)?; write!(f, " at byte pos {pos}")?;
} }
Ok(()) Ok(())
} }
@ -1134,7 +1134,7 @@ impl fmt::Display for FromVecWithNulError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.error_kind { match self.error_kind {
FromBytesWithNulErrorKind::InteriorNul(pos) => { FromBytesWithNulErrorKind::InteriorNul(pos) => {
write!(f, "data provided contains an interior nul byte at pos {}", pos) write!(f, "data provided contains an interior nul byte at pos {pos}")
} }
FromBytesWithNulErrorKind::NotNulTerminated => { FromBytesWithNulErrorKind::NotNulTerminated => {
write!(f, "data provided is not nul terminated") write!(f, "data provided is not nul terminated")

View file

@ -35,7 +35,7 @@ fn build_with_zero2() {
#[test] #[test]
fn formatted() { fn formatted() {
let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap(); let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#); assert_eq!(format!("{s:?}"), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
} }
#[test] #[test]

View file

@ -1123,7 +1123,7 @@ impl Metadata {
/// let metadata = fs::metadata("foo.txt")?; /// let metadata = fs::metadata("foo.txt")?;
/// ///
/// if let Ok(time) = metadata.modified() { /// if let Ok(time) = metadata.modified() {
/// println!("{:?}", time); /// println!("{time:?}");
/// } else { /// } else {
/// println!("Not supported on this platform"); /// println!("Not supported on this platform");
/// } /// }
@ -1158,7 +1158,7 @@ impl Metadata {
/// let metadata = fs::metadata("foo.txt")?; /// let metadata = fs::metadata("foo.txt")?;
/// ///
/// if let Ok(time) = metadata.accessed() { /// if let Ok(time) = metadata.accessed() {
/// println!("{:?}", time); /// println!("{time:?}");
/// } else { /// } else {
/// println!("Not supported on this platform"); /// println!("Not supported on this platform");
/// } /// }
@ -1190,7 +1190,7 @@ impl Metadata {
/// let metadata = fs::metadata("foo.txt")?; /// let metadata = fs::metadata("foo.txt")?;
/// ///
/// if let Ok(time) = metadata.created() { /// if let Ok(time) = metadata.created() {
/// println!("{:?}", time); /// println!("{time:?}");
/// } else { /// } else {
/// println!("Not supported on this platform or filesystem"); /// println!("Not supported on this platform or filesystem");
/// } /// }

View file

@ -30,7 +30,7 @@ macro_rules! check {
($e:expr) => { ($e:expr) => {
match $e { match $e {
Ok(t) => t, Ok(t) => t,
Err(e) => panic!("{} failed with: {}", stringify!($e), e), Err(e) => panic!("{} failed with: {e}", stringify!($e)),
} }
}; };
} }
@ -470,7 +470,7 @@ fn file_test_directoryinfo_readdir() {
check!(fs::create_dir(dir)); check!(fs::create_dir(dir));
let prefix = "foo"; let prefix = "foo";
for n in 0..3 { for n in 0..3 {
let f = dir.join(&format!("{}.txt", n)); let f = dir.join(&format!("{n}.txt"));
let mut w = check!(File::create(&f)); let mut w = check!(File::create(&f));
let msg_str = format!("{}{}", prefix, n.to_string()); let msg_str = format!("{}{}", prefix, n.to_string());
let msg = msg_str.as_bytes(); let msg = msg_str.as_bytes();
@ -1329,7 +1329,7 @@ fn dir_entry_methods() {
assert!(file.file_type().unwrap().is_file()); assert!(file.file_type().unwrap().is_file());
assert!(file.metadata().unwrap().is_file()); assert!(file.metadata().unwrap().is_file());
} }
f => panic!("unknown file name: {:?}", f), f => panic!("unknown file name: {f:?}"),
} }
} }
} }
@ -1340,7 +1340,7 @@ fn dir_entry_debug() {
File::create(&tmpdir.join("b")).unwrap(); File::create(&tmpdir.join("b")).unwrap();
let mut read_dir = tmpdir.path().read_dir().unwrap(); let mut read_dir = tmpdir.path().read_dir().unwrap();
let dir_entry = read_dir.next().unwrap().unwrap(); let dir_entry = read_dir.next().unwrap().unwrap();
let actual = format!("{:?}", dir_entry); let actual = format!("{dir_entry:?}");
let expected = format!("DirEntry({:?})", dir_entry.0.path()); let expected = format!("DirEntry({:?})", dir_entry.0.path());
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }
@ -1409,7 +1409,7 @@ fn metadata_access_times() {
|| e1.kind() == ErrorKind::Unsupported || e1.kind() == ErrorKind::Unsupported
&& e2.kind() == ErrorKind::Unsupported => {} && e2.kind() == ErrorKind::Unsupported => {}
(a, b) => { (a, b) => {
panic!("creation time must be always supported or not supported: {:?} {:?}", a, b,) panic!("creation time must be always supported or not supported: {a:?} {b:?}")
} }
} }
} }

View file

@ -41,7 +41,7 @@ use crate::mem::MaybeUninit;
/// ///
/// let mut line = String::new(); /// let mut line = String::new();
/// let len = reader.read_line(&mut line)?; /// let len = reader.read_line(&mut line)?;
/// println!("First line is {} bytes long", len); /// println!("First line is {len} bytes long");
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```

View file

@ -457,7 +457,7 @@ impl From<ErrorKind> for Error {
/// ///
/// let not_found = ErrorKind::NotFound; /// let not_found = ErrorKind::NotFound;
/// let error = Error::from(not_found); /// let error = Error::from(not_found);
/// assert_eq!("entity not found", format!("{}", error)); /// assert_eq!("entity not found", format!("{error}"));
/// ``` /// ```
#[inline] #[inline]
fn from(kind: ErrorKind) -> Error { fn from(kind: ErrorKind) -> Error {
@ -561,7 +561,7 @@ impl Error {
/// use std::io::Error; /// use std::io::Error;
/// ///
/// let os_error = Error::last_os_error(); /// let os_error = Error::last_os_error();
/// println!("last OS error: {:?}", os_error); /// println!("last OS error: {os_error:?}");
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[must_use] #[must_use]
@ -618,7 +618,7 @@ impl Error {
/// ///
/// fn print_os_error(err: &Error) { /// fn print_os_error(err: &Error) {
/// if let Some(raw_os_err) = err.raw_os_error() { /// if let Some(raw_os_err) = err.raw_os_error() {
/// println!("raw OS error: {:?}", raw_os_err); /// println!("raw OS error: {raw_os_err:?}");
/// } else { /// } else {
/// println!("Not an OS error"); /// println!("Not an OS error");
/// } /// }
@ -657,7 +657,7 @@ impl Error {
/// ///
/// fn print_error(err: &Error) { /// fn print_error(err: &Error) {
/// if let Some(inner_err) = err.get_ref() { /// if let Some(inner_err) = err.get_ref() {
/// println!("Inner error: {:?}", inner_err); /// println!("Inner error: {inner_err:?}");
/// } else { /// } else {
/// println!("No inner error"); /// println!("No inner error");
/// } /// }
@ -731,7 +731,7 @@ impl Error {
/// ///
/// fn print_error(err: &Error) { /// fn print_error(err: &Error) {
/// if let Some(inner_err) = err.get_ref() { /// if let Some(inner_err) = err.get_ref() {
/// println!("Inner error: {}", inner_err); /// println!("Inner error: {inner_err}");
/// } else { /// } else {
/// println!("No inner error"); /// println!("No inner error");
/// } /// }
@ -770,7 +770,7 @@ impl Error {
/// ///
/// fn print_error(err: Error) { /// fn print_error(err: Error) {
/// if let Some(inner_err) = err.into_inner() { /// if let Some(inner_err) = err.into_inner() {
/// println!("Inner error: {}", inner_err); /// println!("Inner error: {inner_err}");
/// } else { /// } else {
/// println!("No inner error"); /// println!("No inner error");
/// } /// }
@ -852,7 +852,7 @@ impl fmt::Display for Error {
match self.repr.data() { match self.repr.data() {
ErrorData::Os(code) => { ErrorData::Os(code) => {
let detail = sys::os::error_string(code); let detail = sys::os::error_string(code);
write!(fmt, "{} (os error {})", detail, code) write!(fmt, "{detail} (os error {code})")
} }
ErrorData::Custom(ref c) => c.error.fmt(fmt), ErrorData::Custom(ref c) => c.error.fmt(fmt),
ErrorData::Simple(kind) => write!(fmt, "{}", kind.as_str()), ErrorData::Simple(kind) => write!(fmt, "{}", kind.as_str()),

View file

@ -161,8 +161,7 @@ impl Repr {
// only run in libstd's tests, unless the user uses -Zbuild-std) // only run in libstd's tests, unless the user uses -Zbuild-std)
debug_assert!( debug_assert!(
matches!(res.data(), ErrorData::Os(c) if c == code), matches!(res.data(), ErrorData::Os(c) if c == code),
"repr(os) encoding failed for {}", "repr(os) encoding failed for {code}"
code,
); );
res res
} }

View file

@ -33,7 +33,7 @@ fn test_debug_error() {
}}", }}",
code, kind, msg code, kind, msg
); );
assert_eq!(format!("{:?}", err), expected); assert_eq!(format!("{err:?}"), expected);
} }
#[test] #[test]
@ -65,8 +65,8 @@ fn test_const() {
assert_eq!(E.kind(), ErrorKind::NotFound); assert_eq!(E.kind(), ErrorKind::NotFound);
assert_eq!(E.to_string(), "hello"); assert_eq!(E.to_string(), "hello");
assert!(format!("{:?}", E).contains("\"hello\"")); assert!(format!("{E:?}").contains("\"hello\""));
assert!(format!("{:?}", E).contains("NotFound")); assert!(format!("{E:?}").contains("NotFound"));
} }
#[test] #[test]
@ -101,7 +101,7 @@ fn test_simple_message_packing() {
let e = &$err; let e = &$err;
// Check that the public api is right. // Check that the public api is right.
assert_eq!(e.kind(), $kind); assert_eq!(e.kind(), $kind);
assert!(format!("{:?}", e).contains($msg)); assert!(format!("{e:?}").contains($msg));
// and we got what we expected // and we got what we expected
assert_matches!( assert_matches!(
e.repr.data(), e.repr.data(),

View file

@ -91,7 +91,7 @@
//! // read a line into buffer //! // read a line into buffer
//! reader.read_line(&mut buffer)?; //! reader.read_line(&mut buffer)?;
//! //!
//! println!("{}", buffer); //! println!("{buffer}");
//! Ok(()) //! Ok(())
//! } //! }
//! ``` //! ```
@ -1035,7 +1035,7 @@ pub trait Read {
/// fn main() -> io::Result<()> { /// fn main() -> io::Result<()> {
/// let stdin = io::read_to_string(io::stdin())?; /// let stdin = io::read_to_string(io::stdin())?;
/// println!("Stdin was:"); /// println!("Stdin was:");
/// println!("{}", stdin); /// println!("{stdin}");
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
@ -1761,7 +1761,7 @@ pub trait Seek {
/// .open("foo.txt").unwrap(); /// .open("foo.txt").unwrap();
/// ///
/// let hello = "Hello!\n"; /// let hello = "Hello!\n";
/// write!(f, "{}", hello).unwrap(); /// write!(f, "{hello}").unwrap();
/// f.rewind().unwrap(); /// f.rewind().unwrap();
/// ///
/// let mut buf = String::new(); /// let mut buf = String::new();
@ -1804,7 +1804,7 @@ pub trait Seek {
/// let mut f = File::open("foo.txt")?; /// let mut f = File::open("foo.txt")?;
/// ///
/// let len = f.stream_len()?; /// let len = f.stream_len()?;
/// println!("The file is currently {} bytes long", len); /// println!("The file is currently {len} bytes long");
/// Ok(()) /// Ok(())
/// } /// }
/// ``` /// ```
@ -1988,7 +1988,7 @@ pub trait BufRead: Read {
/// let buffer = stdin.fill_buf().unwrap(); /// let buffer = stdin.fill_buf().unwrap();
/// ///
/// // work with buffer /// // work with buffer
/// println!("{:?}", buffer); /// println!("{buffer:?}");
/// ///
/// // ensure the bytes we worked with aren't returned again later /// // ensure the bytes we worked with aren't returned again later
/// let length = buffer.len(); /// let length = buffer.len();
@ -2042,7 +2042,7 @@ pub trait BufRead: Read {
/// let mut line = String::new(); /// let mut line = String::new();
/// stdin.read_line(&mut line).unwrap(); /// stdin.read_line(&mut line).unwrap();
/// // work with line /// // work with line
/// println!("{:?}", line); /// println!("{line:?}");
/// } /// }
/// ``` /// ```
#[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")] #[unstable(feature = "buf_read_has_data_left", reason = "recently added", issue = "86423")]

View file

@ -349,10 +349,10 @@ impl Stdin {
/// let mut input = String::new(); /// let mut input = String::new();
/// match io::stdin().read_line(&mut input) { /// match io::stdin().read_line(&mut input) {
/// Ok(n) => { /// Ok(n) => {
/// println!("{} bytes read", n); /// println!("{n} bytes read");
/// println!("{}", input); /// println!("{input}");
/// } /// }
/// Err(error) => println!("error: {}", error), /// Err(error) => println!("error: {error}"),
/// } /// }
/// ``` /// ```
/// ///
@ -953,7 +953,7 @@ where
} }
if let Err(e) = global_s().write_fmt(args) { if let Err(e) = global_s().write_fmt(args) {
panic!("failed printing to {}: {}", label, e); panic!("failed printing to {label}: {e}");
} }
} }

View file

@ -64,7 +64,7 @@ mod as_keyword {}
/// } /// }
/// ///
/// assert_eq!(last, 12); /// assert_eq!(last, 12);
/// println!("{}", last); /// println!("{last}");
/// ``` /// ```
/// ///
/// A break expression is normally associated with the innermost loop enclosing the /// A break expression is normally associated with the innermost loop enclosing the
@ -72,10 +72,10 @@ mod as_keyword {}
/// ///
///```rust ///```rust
/// 'outer: for i in 1..=5 { /// 'outer: for i in 1..=5 {
/// println!("outer iteration (i): {}", i); /// println!("outer iteration (i): {i}");
/// ///
/// '_inner: for j in 1..=200 { /// '_inner: for j in 1..=200 {
/// println!(" inner iteration (j): {}", j); /// println!(" inner iteration (j): {j}");
/// if j >= 3 { /// if j >= 3 {
/// // breaks from inner loop, lets outer loop continue. /// // breaks from inner loop, lets outer loop continue.
/// break; /// break;
@ -106,7 +106,7 @@ mod as_keyword {}
/// }; /// };
/// // first number in Fibonacci sequence over 10: /// // first number in Fibonacci sequence over 10:
/// assert_eq!(result, 13); /// assert_eq!(result, 13);
/// println!("{}", result); /// println!("{result}");
/// ``` /// ```
/// ///
/// For more details consult the [Reference on "break expression"] and the [Reference on "break and /// For more details consult the [Reference on "break expression"] and the [Reference on "break and
@ -200,7 +200,7 @@ mod const_keyword {}
/// if number % 2 == 0 { /// if number % 2 == 0 {
/// continue; /// continue;
/// } /// }
/// println!("{}", number); /// println!("{number}");
/// } /// }
///``` ///```
/// ///
@ -515,7 +515,7 @@ mod fn_keyword {}
/// } /// }
/// ///
/// for i in std::iter::repeat(5) { /// for i in std::iter::repeat(5) {
/// println!("turns out {} never stops being 5", i); /// println!("turns out {i} never stops being 5");
/// break; // would loop forever otherwise /// break; // would loop forever otherwise
/// } /// }
/// ///
@ -776,7 +776,7 @@ mod in_keyword {}
/// let shadowing_example = true; /// let shadowing_example = true;
/// let shadowing_example = 123.4; /// let shadowing_example = 123.4;
/// let shadowing_example = shadowing_example as u32; /// let shadowing_example = shadowing_example as u32;
/// let mut shadowing_example = format!("cool! {}", shadowing_example); /// let mut shadowing_example = format!("cool! {shadowing_example}");
/// shadowing_example += " something else!"; // not shadowing /// shadowing_example += " something else!"; // not shadowing
/// ``` /// ```
/// ///
@ -805,7 +805,7 @@ mod let_keyword {}
/// let mut counter = 0; /// let mut counter = 0;
/// ///
/// while counter < 10 { /// while counter < 10 {
/// println!("{}", counter); /// println!("{counter}");
/// counter += 1; /// counter += 1;
/// } /// }
/// ``` /// ```
@ -836,7 +836,7 @@ mod let_keyword {}
/// if i == 10 { /// if i == 10 {
/// counter = None; /// counter = None;
/// } else { /// } else {
/// println!("{}", i); /// println!("{i}");
/// counter = Some (i + 1); /// counter = Some (i + 1);
/// } /// }
/// } /// }
@ -866,7 +866,7 @@ mod while_keyword {}
/// ///
/// let mut i = 1; /// let mut i = 1;
/// loop { /// loop {
/// println!("i is {}", i); /// println!("i is {i}");
/// if i > 100 { /// if i > 100 {
/// break; /// break;
/// } /// }
@ -920,8 +920,8 @@ mod loop_keyword {}
/// ///
/// let a_number = Option::Some(10); /// let a_number = Option::Some(10);
/// match a_number { /// match a_number {
/// Some(x) if x <= 5 => println!("0 to 5 num = {}", x), /// Some(x) if x <= 5 => println!("0 to 5 num = {x}"),
/// Some(x @ 6..=10) => println!("6 to 10 num = {}", x), /// Some(x @ 6..=10) => println!("6 to 10 num = {x}"),
/// None => panic!(), /// None => panic!(),
/// // all other numbers /// // all other numbers
/// _ => panic!(), /// _ => panic!(),
@ -940,8 +940,8 @@ mod loop_keyword {}
/// ///
/// let get_inner = Outer::Double(None, Some(String::new())); /// let get_inner = Outer::Double(None, Some(String::new()));
/// match get_inner { /// match get_inner {
/// Outer::Double(None, Some(st)) => println!("{}", st), /// Outer::Double(None, Some(st)) => println!("{st}"),
/// Outer::Single(opt) => println!("{:?}", opt), /// Outer::Single(opt) => println!("{opt:?}"),
/// _ => panic!(), /// _ => panic!(),
/// } /// }
/// ``` /// ```
@ -988,7 +988,7 @@ mod mod_keyword {}
/// ///
/// ```rust /// ```rust
/// let data = vec![1, 2, 3]; /// let data = vec![1, 2, 3];
/// let closure = move || println!("captured {:?} by value", data); /// let closure = move || println!("captured {data:?} by value");
/// ///
/// // data is no longer available, it is owned by the closure /// // data is no longer available, it is owned by the closure
/// ``` /// ```
@ -1001,7 +1001,7 @@ mod mod_keyword {}
/// ```rust /// ```rust
/// fn create_fn() -> impl Fn() { /// fn create_fn() -> impl Fn() {
/// let text = "Fn".to_owned(); /// let text = "Fn".to_owned();
/// move || println!("This is a: {}", text) /// move || println!("This is a: {text}")
/// } /// }
/// ///
/// let fn_plain = create_fn(); /// let fn_plain = create_fn();
@ -1014,7 +1014,7 @@ mod mod_keyword {}
/// let data = vec![1, 2, 3]; /// let data = vec![1, 2, 3];
/// ///
/// std::thread::spawn(move || { /// std::thread::spawn(move || {
/// println!("captured {:?} by value", data) /// println!("captured {data:?} by value")
/// }).join().unwrap(); /// }).join().unwrap();
/// ///
/// // data was moved to the spawned thread, so we cannot use it here /// // data was moved to the spawned thread, so we cannot use it here
@ -1025,7 +1025,7 @@ mod mod_keyword {}
/// ```rust /// ```rust
/// let capture = "hello".to_owned(); /// let capture = "hello".to_owned();
/// let block = async move { /// let block = async move {
/// println!("rust says {} from async block", capture); /// println!("rust says {capture} from async block");
/// }; /// };
/// ``` /// ```
/// ///
@ -1124,7 +1124,7 @@ mod pub_keyword {}
/// let maybe_name = Some(String::from("Alice")); /// let maybe_name = Some(String::from("Alice"));
/// // The variable 'maybe_name' is consumed here ... /// // The variable 'maybe_name' is consumed here ...
/// match maybe_name { /// match maybe_name {
/// Some(n) => println!("Hello, {}", n), /// Some(n) => println!("Hello, {n}"),
/// _ => println!("Hello, world"), /// _ => println!("Hello, world"),
/// } /// }
/// // ... and is now unavailable. /// // ... and is now unavailable.
@ -1138,7 +1138,7 @@ mod pub_keyword {}
/// let maybe_name = Some(String::from("Alice")); /// let maybe_name = Some(String::from("Alice"));
/// // Using `ref`, the value is borrowed, not moved ... /// // Using `ref`, the value is borrowed, not moved ...
/// match maybe_name { /// match maybe_name {
/// Some(ref n) => println!("Hello, {}", n), /// Some(ref n) => println!("Hello, {n}"),
/// _ => println!("Hello, world"), /// _ => println!("Hello, world"),
/// } /// }
/// // ... so it's available here! /// // ... so it's available here!
@ -1423,7 +1423,7 @@ mod self_upper_keyword {}
/// // With a strictly read-only static, references will have the same address /// // With a strictly read-only static, references will have the same address
/// assert_eq!(r1, r2); /// assert_eq!(r1, r2);
/// // A static item can be used just like a variable in many cases /// // A static item can be used just like a variable in many cases
/// println!("{:?}", FOO); /// println!("{FOO:?}");
/// ``` /// ```
/// ///
/// # Mutable `static`s /// # Mutable `static`s
@ -1675,7 +1675,7 @@ mod super_keyword {}
/// # #![allow(dead_code)] /// # #![allow(dead_code)]
/// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug { /// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
/// for elem in it { /// for elem in it {
/// println!("{:#?}", elem); /// println!("{elem:#?}");
/// } /// }
/// } /// }
/// ///
@ -2313,7 +2313,7 @@ mod dyn_keyword {}
/// match u { /// match u {
/// IntOrFloat { i: 10 } => println!("Found exactly ten!"), /// IntOrFloat { i: 10 } => println!("Found exactly ten!"),
/// // Matching the field `f` provides an `f32`. /// // Matching the field `f` provides an `f32`.
/// IntOrFloat { f } => println!("Found f = {} !", f), /// IntOrFloat { f } => println!("Found f = {f} !"),
/// } /// }
/// } /// }
/// ``` /// ```
@ -2337,7 +2337,7 @@ mod dyn_keyword {}
/// let i = unsafe { &mut u.i }; /// let i = unsafe { &mut u.i };
/// ///
/// *i = 10; /// *i = 10;
/// println!("f = {} and i = {}", f, i); /// println!("f = {f} and i = {i}");
/// ``` /// ```
/// ///
/// See the [Reference][union] for more informations on `union`s. /// See the [Reference][union] for more informations on `union`s.

View file

@ -169,30 +169,30 @@ fn is_v6() {
fn socket_v4_to_str() { fn socket_v4_to_str() {
let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080); let socket = SocketAddrV4::new(Ipv4Addr::new(192, 168, 0, 1), 8080);
assert_eq!(format!("{}", socket), "192.168.0.1:8080"); assert_eq!(format!("{socket}"), "192.168.0.1:8080");
assert_eq!(format!("{:<20}", socket), "192.168.0.1:8080 "); assert_eq!(format!("{socket:<20}"), "192.168.0.1:8080 ");
assert_eq!(format!("{:>20}", socket), " 192.168.0.1:8080"); assert_eq!(format!("{socket:>20}"), " 192.168.0.1:8080");
assert_eq!(format!("{:^20}", socket), " 192.168.0.1:8080 "); assert_eq!(format!("{socket:^20}"), " 192.168.0.1:8080 ");
assert_eq!(format!("{:.10}", socket), "192.168.0."); assert_eq!(format!("{socket:.10}"), "192.168.0.");
} }
#[test] #[test]
fn socket_v6_to_str() { fn socket_v6_to_str() {
let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0); let mut socket = SocketAddrV6::new(Ipv6Addr::new(0x2a02, 0x6b8, 0, 1, 0, 0, 0, 1), 53, 0, 0);
assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1]:53"); assert_eq!(format!("{socket}"), "[2a02:6b8:0:1::1]:53");
assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1]:53 "); assert_eq!(format!("{socket:<24}"), "[2a02:6b8:0:1::1]:53 ");
assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1]:53"); assert_eq!(format!("{socket:>24}"), " [2a02:6b8:0:1::1]:53");
assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1]:53 "); assert_eq!(format!("{socket:^24}"), " [2a02:6b8:0:1::1]:53 ");
assert_eq!(format!("{:.15}", socket), "[2a02:6b8:0:1::"); assert_eq!(format!("{socket:.15}"), "[2a02:6b8:0:1::");
socket.set_scope_id(5); socket.set_scope_id(5);
assert_eq!(format!("{}", socket), "[2a02:6b8:0:1::1%5]:53"); assert_eq!(format!("{socket}"), "[2a02:6b8:0:1::1%5]:53");
assert_eq!(format!("{:<24}", socket), "[2a02:6b8:0:1::1%5]:53 "); assert_eq!(format!("{socket:<24}"), "[2a02:6b8:0:1::1%5]:53 ");
assert_eq!(format!("{:>24}", socket), " [2a02:6b8:0:1::1%5]:53"); assert_eq!(format!("{socket:>24}"), " [2a02:6b8:0:1::1%5]:53");
assert_eq!(format!("{:^24}", socket), " [2a02:6b8:0:1::1%5]:53 "); assert_eq!(format!("{socket:^24}"), " [2a02:6b8:0:1::1%5]:53 ");
assert_eq!(format!("{:.18}", socket), "[2a02:6b8:0:1::1%5"); assert_eq!(format!("{socket:.18}"), "[2a02:6b8:0:1::1%5");
} }
#[test] #[test]

View file

@ -595,10 +595,10 @@ impl TcpStream {
/// // via platform-specific APIs such as epoll or IOCP /// // via platform-specific APIs such as epoll or IOCP
/// wait_for_fd(); /// wait_for_fd();
/// } /// }
/// Err(e) => panic!("encountered IO error: {}", e), /// Err(e) => panic!("encountered IO error: {e}"),
/// }; /// };
/// }; /// };
/// println!("bytes: {:?}", buf); /// println!("bytes: {buf:?}");
/// ``` /// ```
#[stable(feature = "net2_mutators", since = "1.9.0")] #[stable(feature = "net2_mutators", since = "1.9.0")]
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
@ -799,8 +799,8 @@ impl TcpListener {
/// ///
/// let listener = TcpListener::bind("127.0.0.1:8080").unwrap(); /// let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
/// match listener.accept() { /// match listener.accept() {
/// Ok((_socket, addr)) => println!("new client: {:?}", addr), /// Ok((_socket, addr)) => println!("new client: {addr:?}"),
/// Err(e) => println!("couldn't get client: {:?}", e), /// Err(e) => println!("couldn't get client: {e:?}"),
/// } /// }
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
@ -991,7 +991,7 @@ impl TcpListener {
/// wait_for_fd(); /// wait_for_fd();
/// continue; /// continue;
/// } /// }
/// Err(e) => panic!("encountered IO error: {}", e), /// Err(e) => panic!("encountered IO error: {e}"),
/// } /// }
/// } /// }
/// ``` /// ```

View file

@ -142,8 +142,7 @@ fn write_close() {
e.kind() == ErrorKind::ConnectionReset e.kind() == ErrorKind::ConnectionReset
|| e.kind() == ErrorKind::BrokenPipe || e.kind() == ErrorKind::BrokenPipe
|| e.kind() == ErrorKind::ConnectionAborted, || e.kind() == ErrorKind::ConnectionAborted,
"unknown error: {}", "unknown error: {e}"
e
); );
} }
} }
@ -655,7 +654,7 @@ fn debug() {
inner_name, inner_name,
render_inner(&listener) render_inner(&listener)
); );
assert_eq!(format!("{:?}", listener), compare); assert_eq!(format!("{listener:?}"), compare);
let stream = t!(TcpStream::connect(&("localhost", socket_addr.port()))); let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
let compare = format!( let compare = format!(
@ -665,7 +664,7 @@ fn debug() {
inner_name, inner_name,
render_inner(&stream) render_inner(&stream)
); );
assert_eq!(format!("{:?}", stream), compare); assert_eq!(format!("{stream:?}"), compare);
} }
// FIXME: re-enabled openbsd tests once their socket timeout code // FIXME: re-enabled openbsd tests once their socket timeout code
@ -832,7 +831,7 @@ fn set_nonblocking() {
match stream.read(&mut buf) { match stream.read(&mut buf) {
Ok(_) => panic!("expected error"), Ok(_) => panic!("expected error"),
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {} Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => panic!("unexpected error {}", e), Err(e) => panic!("unexpected error {e}"),
} }
} }
@ -862,7 +861,7 @@ fn peek() {
match c.peek(&mut b) { match c.peek(&mut b) {
Ok(_) => panic!("expected error"), Ok(_) => panic!("expected error"),
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {} Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => panic!("unexpected error {}", e), Err(e) => panic!("unexpected error {e}"),
} }
t!(txdone.send(())); t!(txdone.send(()));
}) })

View file

@ -605,9 +605,9 @@ impl UdpSocket {
/// ///
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address"); /// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
/// match socket.take_error() { /// match socket.take_error() {
/// Ok(Some(error)) => println!("UdpSocket error: {:?}", error), /// Ok(Some(error)) => println!("UdpSocket error: {error:?}"),
/// Ok(None) => println!("No error"), /// Ok(None) => println!("No error"),
/// Err(error) => println!("UdpSocket.take_error failed: {:?}", error), /// Err(error) => println!("UdpSocket.take_error failed: {error:?}"),
/// } /// }
/// ``` /// ```
#[stable(feature = "net2_mutators", since = "1.9.0")] #[stable(feature = "net2_mutators", since = "1.9.0")]
@ -686,8 +686,8 @@ impl UdpSocket {
/// socket.connect("127.0.0.1:8080").expect("connect function failed"); /// socket.connect("127.0.0.1:8080").expect("connect function failed");
/// let mut buf = [0; 10]; /// let mut buf = [0; 10];
/// match socket.recv(&mut buf) { /// match socket.recv(&mut buf) {
/// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]), /// Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
/// Err(e) => println!("recv function failed: {:?}", e), /// Err(e) => println!("recv function failed: {e:?}"),
/// } /// }
/// ``` /// ```
#[stable(feature = "net2_mutators", since = "1.9.0")] #[stable(feature = "net2_mutators", since = "1.9.0")]
@ -726,8 +726,8 @@ impl UdpSocket {
/// socket.connect("127.0.0.1:8080").expect("connect function failed"); /// socket.connect("127.0.0.1:8080").expect("connect function failed");
/// let mut buf = [0; 10]; /// let mut buf = [0; 10];
/// match socket.peek(&mut buf) { /// match socket.peek(&mut buf) {
/// Ok(received) => println!("received {} bytes", received), /// Ok(received) => println!("received {received} bytes"),
/// Err(e) => println!("peek function failed: {:?}", e), /// Err(e) => println!("peek function failed: {e:?}"),
/// } /// }
/// ``` /// ```
#[stable(feature = "peek", since = "1.18.0")] #[stable(feature = "peek", since = "1.18.0")]
@ -770,7 +770,7 @@ impl UdpSocket {
/// // via platform-specific APIs such as epoll or IOCP /// // via platform-specific APIs such as epoll or IOCP
/// wait_for_fd(); /// wait_for_fd();
/// } /// }
/// Err(e) => panic!("encountered IO error: {}", e), /// Err(e) => panic!("encountered IO error: {e}"),
/// } /// }
/// }; /// };
/// println!("bytes: {:?}", &buf[..num_bytes_read]); /// println!("bytes: {:?}", &buf[..num_bytes_read]);

Some files were not shown because too many files have changed in this diff Show more