Rollup merge of #93950 - T-O-R-U-S:use-modern-formatting-for-format!-macros, r=Mark-Simulacrum

Use modern formatting for format! macros

This updates the standard library's documentation to use the new format_args 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).

`eprintln!("{}", e)` becomes `eprintln!("{e}")`, but `eprintln!("{}", e.kind())` remains untouched.
This commit is contained in:
Dylan DPC 2022-03-10 23:12:57 +01:00 committed by GitHub
commit 5a7f09d9a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
177 changed files with 724 additions and 734 deletions

View File

@ -1087,12 +1087,12 @@ impl HandlerInner {
let warnings = match self.deduplicated_warn_count {
0 => String::new(),
1 => "1 warning emitted".to_string(),
count => format!("{} warnings emitted", count),
count => format!("{count} warnings emitted"),
};
let errors = match self.deduplicated_err_count {
0 => String::new(),
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() {
return;

View File

@ -3399,7 +3399,7 @@ declare_lint! {
/// // ^^^^^^^^
/// // 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.
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
///

View File

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

View File

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

View File

@ -397,7 +397,7 @@ pub mod __alloc_error_handler {
// if there is no `#[alloc_error_handler]`
#[rustc_std_internal_symbol]
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]`

View File

@ -161,7 +161,7 @@ where
/// let readonly = [1, 2];
/// let borrowed = Items::new((&readonly[..]).into());
/// match borrowed {
/// Items { values: Cow::Borrowed(b) } => println!("borrowed {:?}", b),
/// Items { values: Cow::Borrowed(b) } => println!("borrowed {b:?}"),
/// _ => 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))));
//! println!("{:?}", list);
//! println!("{list:?}");
//! ```
//!
//! This will print `Cons(1, Cons(2, Nil))`.
@ -1407,7 +1407,7 @@ impl<T: Copy> From<&[T]> for Box<[T]> {
/// let slice: &[u8] = &[104, 101, 108, 108, 111];
/// let boxed_slice: Box<[u8]> = Box::from(slice);
///
/// println!("{:?}", boxed_slice);
/// println!("{boxed_slice:?}");
/// ```
fn from(slice: &[T]) -> Box<[T]> {
let len = slice.len();
@ -1449,7 +1449,7 @@ impl From<&str> for Box<str> {
///
/// ```rust
/// let boxed: Box<str> = Box::from("hello");
/// println!("{}", boxed);
/// println!("{boxed}");
/// ```
#[inline]
fn from(s: &str) -> Box<str> {
@ -1474,14 +1474,14 @@ impl From<Cow<'_, str>> for Box<str> {
///
/// let unboxed = Cow::Borrowed("hello");
/// let boxed: Box<str> = Box::from(unboxed);
/// println!("{}", boxed);
/// println!("{boxed}");
/// ```
///
/// ```rust
/// # use std::borrow::Cow;
/// let unboxed = Cow::Owned("hello".to_string());
/// let boxed: Box<str> = Box::from(unboxed);
/// println!("{}", boxed);
/// println!("{boxed}");
/// ```
#[inline]
fn from(cow: Cow<'_, str>) -> Box<str> {
@ -1528,7 +1528,7 @@ impl<T, const N: usize> From<[T; N]> for Box<[T]> {
///
/// ```rust
/// let boxed: Box<[u8]> = Box::from([4, 2]);
/// println!("{:?}", boxed);
/// println!("{boxed:?}");
/// ```
fn from(array: [T; N]) -> Box<[T]> {
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
/// // a random order.
/// for x in &heap {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // 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
/// for x in heap.iter() {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -1110,7 +1110,7 @@ impl<T> BinaryHeap<T> {
///
/// // Will print in some order
/// for x in vec {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
@ -1179,7 +1179,7 @@ impl<T> BinaryHeap<T> {
/// assert!(!heap.is_empty());
///
/// for x in heap.drain() {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// assert!(heap.is_empty());
@ -1624,7 +1624,7 @@ impl<T> IntoIterator for BinaryHeap<T> {
/// // Print 1, 2, 3, 4 in arbitrary order
/// for x in heap.into_iter() {
/// // x has type i32, not &i32
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
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"];
/// for movie in &to_find {
/// match movie_reviews.get(movie) {
/// Some(review) => println!("{}: {}", movie, review),
/// None => println!("{} is unreviewed.", movie)
/// Some(review) => println!("{movie}: {review}"),
/// None => println!("{movie} is unreviewed.")
/// }
/// }
///
@ -114,7 +114,7 @@ pub(super) const MIN_LEN: usize = node::MIN_LEN_AFTER_SPLIT;
///
/// // iterate over everything.
/// 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(8, "c");
/// 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());
/// ```
@ -1104,7 +1104,7 @@ impl<K, V> BTreeMap<K, V> {
/// *balance += 100;
/// }
/// for (name, balance) in &map {
/// println!("{} => {}", name, balance);
/// println!("{name} => {balance}");
/// }
/// ```
#[stable(feature = "btree_range", since = "1.17.0")]
@ -2088,7 +2088,7 @@ impl<K, V> BTreeMap<K, V> {
/// map.insert(1, "a");
///
/// for (key, value) in map.iter() {
/// println!("{}: {}", key, value);
/// println!("{key}: {value}");
/// }
///
/// 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, ()>) {
format!("{:?}", map);
format!("{map:?}");
format!("{:?}", map.iter());
format!("{:?}", map.iter_mut());
format!("{:?}", map.keys());

View File

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

View File

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

View File

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

View File

@ -309,7 +309,7 @@ fn test_cowrc_clone_weak() {
#[test]
fn test_show() {
let foo = Rc::new(75);
assert_eq!(format!("{:?}", foo), "75");
assert_eq!(format!("{foo:?}"), "75");
}
#[test]
@ -324,7 +324,7 @@ fn test_maybe_thin_unsized() {
use std::ffi::{CStr, CString};
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);
drop(x);
@ -451,7 +451,7 @@ fn test_from_box_trait_zero_sized() {
let b: Box<dyn Debug> = box ();
let r: Rc<dyn Debug> = Rc::from(b);
assert_eq!(format!("{:?}", r), "()");
assert_eq!(format!("{r:?}"), "()");
}
#[test]

View File

@ -48,7 +48,7 @@
//! ```
//! let numbers = &[0, 1, 2];
//! 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);
///
/// for b in v1 {
/// println!("{}", b);
/// println!("{b}");
/// }
/// ```
fn from(string: String) -> Vec<u8> {

View File

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

View File

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

View File

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

View File

@ -169,7 +169,7 @@ mod spec_extend;
/// vec.extend([1, 2, 3].iter().copied());
///
/// for x in &vec {
/// println!("{}", x);
/// println!("{x}");
/// }
/// assert_eq!(vec, [7, 1, 2, 3]);
/// ```
@ -211,7 +211,7 @@ mod spec_extend;
///
/// while let Some(top) = stack.pop() {
/// // Prints 3, 2, 1
/// println!("{}", top);
/// println!("{top}");
/// }
/// ```
///
@ -1297,7 +1297,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold]
#[inline(never)]
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();
@ -1338,7 +1338,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold]
#[inline(never)]
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();
@ -1397,7 +1397,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[inline(never)]
#[track_caller]
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();
@ -1942,7 +1942,7 @@ impl<T, A: Allocator> Vec<T, A> {
#[cold]
#[inline(never)]
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() {
@ -2568,7 +2568,7 @@ impl<T, A: Allocator> IntoIterator for Vec<T, A> {
/// let v = vec!["a".to_string(), "b".to_string()];
/// for s in v.into_iter() {
/// // s has type String, not &String
/// println!("{}", s);
/// println!("{s}");
/// }
/// ```
#[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 *mut isize), "0x1234");
t!(format!("{:x}", A), "aloha");
t!(format!("{:X}", B), "adios");
t!(format!("{A:x}"), "aloha");
t!(format!("{B:X}"), "adios");
t!(format!("foo {} ☃☃☃☃☃☃", "bar"), "foo bar ☃☃☃☃☃☃");
t!(format!("{1} {0}", 0, 1), "1 0");
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_bar}", foo_bar = 1), "1");
t!(format!("{}", 5 + 5), "10");
t!(format!("{:#4}", C), "☃123");
t!(format!("{:b}", D), "aa☃bb");
t!(format!("{C:#4}"), "☃123");
t!(format!("{D:b}"), "aa☃bb");
let a: &dyn fmt::Debug = &1;
t!(format!("{:?}", a), "1");
t!(format!("{a:?}"), "1");
// Formatting strings and their arguments
t!(format!("{}", "a"), "a");
@ -206,7 +206,7 @@ fn test_format_macro_interface() {
// Test that pointers don't get truncated.
{
let val = usize::MAX;
let exp = format!("{:#x}", val);
let exp = format!("{val:#x}");
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
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
// it's inside of an outer unsafe block
unsafe {
let a: isize = ::std::mem::transmute(3_usize);
format!("{}", a);
format!("{a}");
}
// test that trailing commas are acceptable
@ -315,9 +315,9 @@ fn test_once() {
#[test]
fn test_refcell() {
let refcell = RefCell::new(5);
assert_eq!(format!("{:?}", refcell), "RefCell { value: 5 }");
assert_eq!(format!("{refcell:?}"), "RefCell { value: 5 }");
let borrow = refcell.borrow_mut();
assert_eq!(format!("{:?}", refcell), "RefCell { value: <borrowed> }");
assert_eq!(format!("{refcell:?}"), "RefCell { value: <borrowed> }");
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]
fn test_show() {
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();
assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]");
assert_eq!(format!("{list:?}"), "[\"just\", \"one\", \"test\", \"more\"]");
}
#[test]

View File

@ -1045,10 +1045,10 @@ fn test_split_iterators_size_hint() {
a(v.rsplit_mut(p), b, "rsplit_mut");
for n in 0..=3 {
a(v.splitn(n, p), b, f!("splitn, 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_mut(n, p), b, f!("rsplitn_mut, 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.rsplitn(n, p), b, f!("rsplitn, 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 {
($x:expr, $x_str:expr) => {{
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();

View File

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

View File

@ -470,7 +470,7 @@ fn test_simple_types() {
#[test]
fn test_vectors() {
let x: Vec<i32> = vec![];
assert_eq!(format!("{:?}", x), "[]");
assert_eq!(format!("{x:?}"), "[]");
assert_eq!(format!("{:?}", vec![1]), "[1]");
assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]");
assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) == "[[], [1], [1, 1]]");
@ -871,6 +871,6 @@ fn test_from_char() {
fn test_str_concat() {
let a: String = "hello".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);
}

View File

@ -100,7 +100,7 @@ fn test_debug_fmt() {
assert_eq!("[0, 1]", format!("{:?}", vec2));
let slice: &[isize] = &[4, 5];
assert_eq!("[4, 5]", format!("{:?}", slice));
assert_eq!("[4, 5]", format!("{slice:?}"));
}
#[test]
@ -918,7 +918,7 @@ fn test_into_iter_as_mut_slice() {
fn test_into_iter_debug() {
let vec = vec!['a', 'b', 'c'];
let into_iter = vec.into_iter();
let debug = format!("{:?}", into_iter);
let debug = format!("{into_iter:?}");
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);
if !ok {
panic!("expected: {:?}\ngot: {:?}\n", expected, vec);
panic!("expected: {expected:?}\ngot: {vec:?}\n");
}
}

View File

@ -647,10 +647,10 @@ fn test_ord() {
#[test]
fn test_show() {
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();
assert_eq!(format!("{:?}", ringbuf), "[\"just\", \"one\", \"test\", \"more\"]");
assert_eq!(format!("{ringbuf:?}"), "[\"just\", \"one\", \"test\", \"more\"]");
}
#[test]

View File

@ -12,7 +12,7 @@ use test::Bencher;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 {
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 {
match decode(v).1 {
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);
//! }
//! None => {
//! println!("{:?}", value);
//! println!("{value:?}");
//! }
//! }
//! }

View File

@ -85,7 +85,7 @@
//! // of scope then the subsequent borrow would cause a dynamic thread panic.
//! // This is the major hazard of using `RefCell`.
//! 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() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -448,7 +448,7 @@ impl char {
///
/// ```
/// for c in '\n'.escape_debug() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -504,7 +504,7 @@ impl char {
///
/// ```
/// for c in '"'.escape_default() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -949,7 +949,7 @@ impl char {
///
/// ```
/// for c in 'İ'.to_lowercase() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -1016,7 +1016,7 @@ impl char {
///
/// ```
/// for c in 'ß'.to_uppercase() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```

View File

@ -64,7 +64,7 @@ pub mod rt {
///
/// 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")]
pub type Result = result::Result<(), Error>;
@ -174,7 +174,7 @@ pub trait Write {
/// use std::fmt::{Error, Write};
///
/// 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();
@ -562,7 +562,7 @@ impl Display for Arguments<'_> {
///
/// 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:
@ -586,7 +586,7 @@ impl Display for Arguments<'_> {
///
/// 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
@ -627,7 +627,7 @@ impl Display for Arguments<'_> {
///
/// 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 {
/// x: 0,
/// y: 0,
@ -670,9 +670,9 @@ pub trait Debug {
/// }
///
/// 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,
/// 2.983,
/// )");
@ -724,7 +724,7 @@ pub use macros::Debug;
///
/// 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(
on(
@ -786,8 +786,8 @@ pub trait Display {
/// ```
/// let x = 42; // 42 is '52' in octal
///
/// assert_eq!(format!("{:o}", x), "52");
/// assert_eq!(format!("{:#o}", x), "0o52");
/// assert_eq!(format!("{x:o}"), "52");
/// assert_eq!(format!("{x:#o}"), "0o52");
///
/// assert_eq!(format!("{:o}", -16), "37777777760");
/// ```
@ -809,9 +809,9 @@ pub trait Display {
///
/// 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")]
pub trait Octal {
@ -840,8 +840,8 @@ pub trait Octal {
/// ```
/// let x = 42; // 42 is '101010' in binary
///
/// assert_eq!(format!("{:b}", x), "101010");
/// assert_eq!(format!("{:#b}", x), "0b101010");
/// assert_eq!(format!("{x:b}"), "101010");
/// assert_eq!(format!("{x:#b}"), "0b101010");
///
/// assert_eq!(format!("{:b}", -16), "11111111111111111111111111110000");
/// ```
@ -863,10 +863,10 @@ pub trait Octal {
///
/// 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!(
/// format!("l as binary is: {:#032b}", l),
/// format!("l as binary is: {l:#032b}"),
/// "l as binary is: 0b000000000000000000000001101011"
/// );
/// ```
@ -898,8 +898,8 @@ pub trait Binary {
/// ```
/// let x = 42; // 42 is '2a' in hex
///
/// assert_eq!(format!("{:x}", x), "2a");
/// assert_eq!(format!("{:#x}", x), "0x2a");
/// assert_eq!(format!("{x:x}"), "2a");
/// assert_eq!(format!("{x:#x}"), "0x2a");
///
/// assert_eq!(format!("{:x}", -16), "fffffff0");
/// ```
@ -921,9 +921,9 @@ pub trait Binary {
///
/// 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")]
pub trait LowerHex {
@ -953,8 +953,8 @@ pub trait LowerHex {
/// ```
/// let x = 42; // 42 is '2A' in hex
///
/// assert_eq!(format!("{:X}", x), "2A");
/// assert_eq!(format!("{:#X}", x), "0x2A");
/// assert_eq!(format!("{x:X}"), "2A");
/// assert_eq!(format!("{x:#X}"), "0x2A");
///
/// assert_eq!(format!("{:X}", -16), "FFFFFFF0");
/// ```
@ -976,9 +976,9 @@ pub trait LowerHex {
///
/// 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")]
pub trait UpperHex {
@ -1003,7 +1003,7 @@ pub trait UpperHex {
/// ```
/// 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:
@ -1024,9 +1024,9 @@ pub trait UpperHex {
///
/// 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[..2], "0x");
/// ```
@ -1054,7 +1054,7 @@ pub trait Pointer {
/// ```
/// 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:
@ -1074,12 +1074,12 @@ pub trait Pointer {
/// let l = Length(100);
///
/// assert_eq!(
/// format!("l in scientific notation is: {:e}", l),
/// format!("l in scientific notation is: {l:e}"),
/// "l in scientific notation is: 1e2"
/// );
///
/// assert_eq!(
/// format!("l in scientific notation is: {:05e}", l),
/// format!("l in scientific notation is: {l:05e}"),
/// "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
///
/// assert_eq!(format!("{:E}", x), "4.2E1");
/// assert_eq!(format!("{x:E}"), "4.2E1");
/// ```
///
/// Implementing `UpperExp` on a type:
@ -1125,12 +1125,12 @@ pub trait LowerExp {
/// let l = Length(100);
///
/// assert_eq!(
/// format!("l in scientific notation is: {:E}", l),
/// format!("l in scientific notation is: {l:E}"),
/// "l in scientific notation is: 1E2"
/// );
///
/// assert_eq!(
/// format!("l in scientific notation is: {:05E}", l),
/// format!("l in scientific notation is: {l:05E}"),
/// "l in scientific notation is: 001E2"
/// );
/// ```
@ -1429,8 +1429,8 @@ impl<'a> Formatter<'a> {
/// }
/// }
///
/// assert_eq!(&format!("{:<4}", Foo), "Foo ");
/// assert_eq!(&format!("{:0>4}", Foo), "0Foo");
/// assert_eq!(&format!("{Foo:<4}"), "Foo ");
/// assert_eq!(&format!("{Foo:0>4}"), "0Foo");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pad(&mut self, s: &str) -> Result {
@ -1613,8 +1613,8 @@ impl<'a> Formatter<'a> {
/// }
/// }
///
/// assert_eq!(&format!("{}", Foo), "Foo");
/// assert_eq!(&format!("{:0>8}", Foo), "Foo");
/// assert_eq!(&format!("{Foo}"), "Foo");
/// assert_eq!(&format!("{Foo:0>8}"), "Foo");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write_str(&mut self, data: &str) -> Result {
@ -1670,18 +1670,18 @@ impl<'a> Formatter<'a> {
/// let c = formatter.fill();
/// if let Some(width) = formatter.width() {
/// for _ in 0..width {
/// write!(formatter, "{}", c)?;
/// write!(formatter, "{c}")?;
/// }
/// Ok(())
/// } else {
/// write!(formatter, "{}", c)
/// write!(formatter, "{c}")
/// }
/// }
/// }
///
/// // We set alignment to the right with ">".
/// assert_eq!(&format!("{:G>3}", Foo), "GGG");
/// assert_eq!(&format!("{:t>6}", Foo), "tttttt");
/// assert_eq!(&format!("{Foo:G>3}"), "GGG");
/// assert_eq!(&format!("{Foo:t>6}"), "tttttt");
/// ```
#[must_use]
#[stable(feature = "fmt_flags", since = "1.5.0")]
@ -1711,14 +1711,14 @@ impl<'a> Formatter<'a> {
/// } else {
/// "into the void"
/// };
/// write!(formatter, "{}", s)
/// write!(formatter, "{s}")
/// }
/// }
///
/// assert_eq!(&format!("{:<}", Foo), "left");
/// assert_eq!(&format!("{:>}", Foo), "right");
/// assert_eq!(&format!("{:^}", Foo), "center");
/// assert_eq!(&format!("{}", Foo), "into the void");
/// assert_eq!(&format!("{Foo:<}"), "left");
/// assert_eq!(&format!("{Foo:>}"), "right");
/// assert_eq!(&format!("{Foo:^}"), "center");
/// assert_eq!(&format!("{Foo}"), "into the void");
/// ```
#[must_use]
#[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()
/// .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()
/// .map(|letter| { c += 1; (letter, c) })
/// .rev() {
/// println!("{:?}", pair);
/// println!("{pair:?}");
/// }
/// ```
#[must_use = "iterators are lazy and do nothing unless consumed"]

View File

@ -144,7 +144,7 @@
//! let values = vec![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{}", x);
//! println!("{x}");
//! }
//! ```
//!
@ -164,7 +164,7 @@
//! let values = vec![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{}", x);
//! println!("{x}");
//! }
//! ```
//!
@ -181,7 +181,7 @@
//! None => break,
//! };
//! let x = next;
//! let () = { println!("{}", x); };
//! let () = { println!("{x}"); };
//! },
//! };
//! result
@ -280,7 +280,7 @@
//! ```
//! # #![allow(unused_must_use)]
//! 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
@ -297,10 +297,10 @@
//! ```
//! let v = vec![1, 2, 3, 4, 5];
//!
//! v.iter().for_each(|x| println!("{}", x));
//! v.iter().for_each(|x| println!("{x}"));
//! // or
//! for x in &v {
//! println!("{}", x);
//! println!("{x}");
//! }
//! ```
//!
@ -329,7 +329,7 @@
//! let five_numbers = numbers.take(5);
//!
//! for number in five_numbers {
//! println!("{}", number);
//! println!("{number}");
//! }
//! ```
//!
@ -345,7 +345,7 @@
//! let ones = std::iter::repeat(1);
//! let least = ones.min().unwrap(); // Oh no! An infinite loop!
//! // `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

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
/// for f in files {
/// println!("{:?}", f);
/// println!("{f:?}");
/// }
/// ```
#[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
/// for f in files {
/// println!("{:?}", f);
/// println!("{f:?}");
/// }
/// ```
#[inline]

View File

@ -227,7 +227,7 @@ pub trait FromIterator<A>: Sized {
/// {
/// collection
/// .into_iter()
/// .map(|item| format!("{:?}", item))
/// .map(|item| format!("{item:?}"))
/// .collect()
/// }
/// ```
@ -345,7 +345,7 @@ impl<I: Iterator> IntoIterator for I {
/// c.extend(vec![1, 2, 3]);
///
/// // 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")]
pub trait Extend<A> {

View File

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

View File

@ -709,13 +709,13 @@ pub trait Iterator {
/// ```
/// # #![allow(unused_must_use)]
/// // 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.
///
/// // Instead, use for:
/// for x in 0..5 {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[inline]
@ -761,7 +761,7 @@ pub trait Iterator {
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x));
/// .for_each(|(i, x)| println!("{i}:{x}"));
/// ```
#[inline]
#[stable(feature = "iterator_for_each", since = "1.21.0")]
@ -1575,17 +1575,17 @@ pub trait Iterator {
/// .filter(|x| x % 2 == 0)
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
/// println!("{sum}");
///
/// // let's add some inspect() calls to investigate what's happening
/// let sum = a.iter()
/// .cloned()
/// .inspect(|x| println!("about to filter: {}", x))
/// .inspect(|x| println!("about to filter: {x}"))
/// .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);
///
/// println!("{}", sum);
/// println!("{sum}");
/// ```
///
/// This will print:
@ -1611,13 +1611,13 @@ pub trait Iterator {
/// .map(|line| line.parse::<i32>())
/// .inspect(|num| {
/// if let Err(ref e) = *num {
/// println!("Parsing error: {}", e);
/// println!("Parsing error: {e}");
/// }
/// })
/// .filter_map(Result::ok)
/// .sum();
///
/// println!("Sum: {}", sum);
/// println!("Sum: {sum}");
/// ```
///
/// This will print:
@ -2205,7 +2205,7 @@ pub trait Iterator {
///
/// 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());
///
/// let mut it = data.iter().cloned();
@ -2319,7 +2319,7 @@ pub trait Iterator {
/// let zero = "0".to_string();
///
/// let result = numbers.iter().fold(zero, |acc, &x| {
/// format!("({} + {})", acc, x)
/// format!("({acc} + {x})")
/// });
///
/// 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");
/// 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
@ -935,7 +935,7 @@ pub(crate) mod builtin {
///
/// ```
/// 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")]
#[rustc_builtin_macro]
@ -1046,7 +1046,7 @@ pub(crate) mod builtin {
///
/// ```
/// let current_line = line!();
/// println!("defined on line: {}", current_line);
/// println!("defined on line: {current_line}");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro]
@ -1074,7 +1074,7 @@ pub(crate) mod builtin {
///
/// ```
/// 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
@ -1112,7 +1112,7 @@ pub(crate) mod builtin {
///
/// ```
/// let this_file = file!();
/// println!("defined in file: {}", this_file);
/// println!("defined in file: {this_file}");
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_builtin_macro]
@ -1176,7 +1176,7 @@ pub(crate) mod builtin {
/// fn main() {
/// let my_str = include_str!("spanish.in");
/// assert_eq!(my_str, "adiós\n");
/// print!("{}", my_str);
/// print!("{my_str}");
/// }
/// ```
///
@ -1325,7 +1325,7 @@ pub(crate) mod builtin {
/// fn main() {
/// let my_string = include!("monkeys.in");
/// 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
///
/// // 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':
@ -236,7 +236,7 @@ pub trait StructuralEq {
///
/// // `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

View File

@ -163,7 +163,7 @@ from_str_float_impl!(f64);
/// use std::str::FromStr;
///
/// 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)]

View File

@ -61,7 +61,7 @@ impl const From<!> for TryFromIntError {
///
/// ```
/// 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)]

View File

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

View File

@ -653,7 +653,7 @@ impl<Idx: PartialOrd<Idx>> RangeToInclusive<Idx> {
/// map.insert(8, "c");
///
/// 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());

View File

@ -34,7 +34,7 @@
//! // Pattern match to retrieve the value
//! match result {
//! // The division was valid
//! Some(x) => println!("Result: {}", x),
//! Some(x) => println!("Result: {x}"),
//! // The division was invalid
//! None => println!("Cannot divide by 0"),
//! }
@ -66,7 +66,7 @@
//!
//! fn check_optional(optional: Option<Box<i32>>) {
//! match optional {
//! Some(p) => println!("has value {}", p),
//! Some(p) => println!("has value {p}"),
//! None => println!("has no value"),
//! }
//! }
@ -493,7 +493,7 @@
//! }
//!
//! 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 :("),
//! }
//! ```
@ -615,7 +615,7 @@ impl<T> Option<T> {
/// // First, cast `Option<String>` to `Option<&String>` with `as_ref`,
/// // then consume *that* with `map`, leaving `text` on the stack.
/// 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]
#[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];
///
/// // 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
/// 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]
#[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 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));
/// ```

View File

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

View File

@ -39,7 +39,7 @@ use crate::panic::{Location, PanicInfo};
#[rustc_const_unstable(feature = "core_panic", issue = "none")]
#[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
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
// write expr, which calls Formatter::pad, which must accommodate string
// 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()
}
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

View File

@ -607,7 +607,7 @@ mod prim_pointer {}
///
/// // This loop prints: 0 1 2
/// 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.
/// for item in array.into_iter().enumerate() {
/// 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:
/// for item in array.iter().enumerate() {
/// 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`
/// for item in IntoIterator::into_iter(array).enumerate() {
/// 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:
/// for item in array.iter().enumerate() {
/// let (i, x): (usize, &i32) = item;
/// println!("array[{}] = {}", i, x);
/// println!("array[{i}] = {x}");
/// }
///
/// // This iterates by value:
/// for item in array.into_iter().enumerate() {
/// 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:
/// for item in array.iter() {
/// let x: &i32 = item;
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // This iterates by value:
/// for item in IntoIterator::into_iter(array) {
/// let x: i32 = item;
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // This iterates by value:
/// for item in array {
/// let x: i32 = item;
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// // IntoIter can also start a chain.
/// // This iterates by value:
/// for item in IntoIterator::into_iter(array).enumerate() {
/// 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 {
/// 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 {
/// 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")]

View File

@ -160,7 +160,7 @@ impl<T: ?Sized> *mut T {
///
/// unsafe {
/// 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 {
/// 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")]
@ -409,7 +409,7 @@ impl<T: ?Sized> *mut T {
/// let first_value = unsafe { ptr.as_mut().unwrap() };
/// *first_value = 4;
/// # 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
@ -424,7 +424,7 @@ impl<T: ?Sized> *mut T {
/// let first_value = unsafe { &mut *ptr };
/// *first_value = 4;
/// # 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")]
#[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 ref_x = unsafe { ptr.as_ref() };
/// println!("{}", ref_x);
/// println!("{ref_x}");
/// ```
///
/// [the module documentation]: crate::ptr#safety

View File

@ -35,8 +35,8 @@
//!
//! let version = parse_version(&[1, 2, 3, 4]);
//! match version {
//! Ok(v) => println!("working with version: {:?}", v),
//! Err(e) => println!("error parsing header: {:?}", e),
//! Ok(v) => println!("working with version: {v:?}"),
//! Err(e) => println!("error parsing header: {e:?}"),
//! }
//! ```
//!
@ -447,9 +447,9 @@
//! .collect();
//! assert_eq!(errs.len(), 3);
//! assert_eq!(nums, [17, 99]);
//! println!("results {:?}", results);
//! println!("errs {:?}", errs);
//! println!("nums {:?}", nums);
//! println!("results {results:?}");
//! println!("errs {errs:?}");
//! println!("nums {nums:?}");
//! ```
//!
//! ## Collecting into `Result`
@ -756,7 +756,7 @@ impl<T, E> Result<T, E> {
///
/// for num in line.lines() {
/// match num.parse::<i32>().map(|i| i * 2) {
/// Ok(n) => println!("{}", n),
/// Ok(n) => println!("{n}"),
/// Err(..) => {}
/// }
/// }
@ -838,7 +838,7 @@ impl<T, E> Result<T, E> {
/// 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);
/// assert_eq!(x.map_err(stringify), Ok(2));
@ -864,7 +864,7 @@ impl<T, E> Result<T, E> {
///
/// let x: u8 = "4"
/// .parse::<u8>()
/// .inspect(|x| println!("original: {}", x))
/// .inspect(|x| println!("original: {x}"))
/// .map(|x| x.pow(3))
/// .expect("failed to parse number");
/// ```
@ -889,7 +889,7 @@ impl<T, E> Result<T, E> {
///
/// fn read() -> io::Result<String> {
/// 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]
@ -1198,7 +1198,7 @@ impl<T, E> Result<T, E> {
/// }
///
/// let s: String = only_good_news().into_ok();
/// println!("{}", s);
/// println!("{s}");
/// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline]
@ -1235,7 +1235,7 @@ impl<T, E> Result<T, E> {
/// }
///
/// let error: String = only_bad_news().into_err();
/// println!("{}", error);
/// println!("{error}");
/// ```
#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
#[inline]
@ -1781,7 +1781,7 @@ impl<T> Result<T, T> {
#[cold]
#[track_caller]
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`

View File

@ -48,7 +48,7 @@ const fn slice_start_index_len_fail(index: usize, len: usize) -> ! {
// FIXME const-hack
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) -> ! {
@ -69,7 +69,7 @@ const fn slice_end_index_len_fail(index: usize, len: usize) -> ! {
// FIXME const-hack
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) -> ! {
@ -88,7 +88,7 @@ const fn slice_index_order_fail(index: usize, end: usize) -> ! {
// FIXME const-hack
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) -> ! {

View File

@ -55,7 +55,7 @@ fn size_from_ptr<T>(_: *const T) -> usize {
///
/// // Then, we iterate over it:
/// 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]":
/// println!("{:?}", slice);
/// println!("{slice:?}");
/// ```
///
/// [`iter_mut`]: slice::iter_mut
@ -266,7 +266,7 @@ impl<'a, T> IterMut<'a, T> {
/// *iter.next().unwrap() += 1;
/// }
/// // Now slice is "[2, 2, 3]":
/// println!("{:?}", slice);
/// println!("{slice:?}");
/// ```
#[must_use = "`self` will be dropped if the result is not used"]
#[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];
///
/// for group in v.splitn(2, |num| *num % 3 == 0) {
/// println!("{:?}", group);
/// println!("{group:?}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -2067,7 +2067,7 @@ impl<T> [T] {
/// let v = [10, 40, 30, 20, 60, 50];
///
/// for group in v.rsplitn(2, |num| *num % 3 == 0) {
/// println!("{:?}", group);
/// println!("{group:?}");
/// }
/// ```
#[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
if begin > s.len() || end > s.len() {
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
@ -2446,7 +2446,7 @@ impl str {
///
/// ```
/// for c in "❤\n!".escape_debug() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -2492,7 +2492,7 @@ impl str {
///
/// ```
/// for c in "❤\n!".escape_default() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```
@ -2530,7 +2530,7 @@ impl str {
///
/// ```
/// for c in "❤\n!".escape_unicode() {
/// print!("{}", c);
/// print!("{c}");
/// }
/// println!();
/// ```

View File

@ -94,7 +94,7 @@
//! }
//!
//! 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;
/// let atomic_bool = AtomicBool::from(true);
/// assert_eq!(format!("{:?}", atomic_bool), "true")
/// assert_eq!(format!("{atomic_bool:?}"), "true")
/// ```
#[inline]
fn from(b: bool) -> Self {

View File

@ -1214,7 +1214,7 @@ impl fmt::Debug for Duration {
/// use std::time::Duration;
///
/// 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)]

View File

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

View File

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

View File

@ -62,10 +62,10 @@ fn cell_update() {
#[test]
fn cell_has_sensible_show() {
let x = Cell::new("foo bar");
assert!(format!("{:?}", x).contains(x.get()));
assert!(format!("{x:?}").contains(x.get()));
x.set("baz qux");
assert!(format!("{:?}", x).contains(x.get()));
assert!(format!("{x:?}").contains(x.get()));
}
#[test]
@ -73,11 +73,11 @@ fn ref_and_refmut_have_sensible_show() {
let refcell = RefCell::new("foo");
let refcell_refmut = refcell.borrow_mut();
assert!(format!("{:?}", refcell_refmut).contains("foo"));
assert!(format!("{refcell_refmut:?}").contains("foo"));
drop(refcell_refmut);
let refcell_ref = refcell.borrow();
assert!(format!("{:?}", refcell_ref).contains("foo"));
assert!(format!("{refcell_ref:?}").contains("foo"));
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]
@ -25,12 +25,12 @@ mod debug_struct {
}
}
assert_eq!("Foo { bar: true }", format!("{:?}", Foo));
assert_eq!("Foo { bar: true }", format!("{Foo:?}"));
assert_eq!(
"Foo {
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!(
"Foo {
bar: true,
baz: 10/20,
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -80,7 +80,7 @@ mod debug_struct {
assert_eq!(
"Bar { foo: Foo { bar: true, baz: 10/20 }, hello: \"world\" }",
format!("{:?}", Bar)
format!("{Bar:?}")
);
assert_eq!(
"Bar {
@ -90,7 +90,7 @@ mod debug_struct {
},
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]
@ -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!(
"Foo {
bar: true,
baz: 10/20,
..
}",
format!("{:#?}", Foo)
format!("{Foo:#?}")
);
}
@ -158,7 +158,7 @@ mod debug_struct {
assert_eq!(
"Bar { foo: Foo { bar: true, baz: 10/20, .. }, hello: \"world\", .. }",
format!("{:?}", Bar)
format!("{Bar:?}")
);
assert_eq!(
"Bar {
@ -170,7 +170,7 @@ mod debug_struct {
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]
@ -202,12 +202,12 @@ mod debug_tuple {
}
}
assert_eq!("Foo(true)", format!("{:?}", Foo));
assert_eq!("Foo(true)", format!("{Foo:?}"));
assert_eq!(
"Foo(
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!(
"Foo(
true,
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!(
"Bar(
Foo(
@ -258,7 +258,7 @@ mod debug_tuple {
),
\"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]
@ -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!(
"{
\"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!(
"{
\"bar\": true,
10: 10/20,
}",
format!("{:#?}", Entry)
format!("{Entry:#?}")
);
}
@ -373,7 +373,7 @@ mod debug_map {
assert_eq!(
"{\"foo\": {\"bar\": true, 10: 10/20}, \
{\"bar\": true, 10: 10/20}: \"world\"}",
format!("{:?}", Bar)
format!("{Bar:?}")
);
assert_eq!(
"{
@ -386,7 +386,7 @@ mod debug_map {
10: 10/20,
}: \"world\",
}",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
@ -441,7 +441,7 @@ mod debug_map {
}
}
format!("{:?}", Foo);
format!("{Foo:?}");
}
#[test]
@ -455,7 +455,7 @@ mod debug_map {
}
}
format!("{:?}", Foo);
format!("{Foo:?}");
}
#[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]
@ -500,12 +500,12 @@ mod debug_set {
}
}
assert_eq!("{true}", format!("{:?}", Foo));
assert_eq!("{true}", format!("{Foo:?}"));
assert_eq!(
"{
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!(
"{
true,
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!(
"{
{
@ -556,7 +556,7 @@ mod debug_set {
},
\"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]
@ -588,12 +588,12 @@ mod debug_list {
}
}
assert_eq!("[true]", format!("{:?}", Foo));
assert_eq!("[true]", format!("{Foo:?}"));
assert_eq!(
"[
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!(
"[
true,
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!(
"[
[
@ -644,7 +644,7 @@ mod debug_list {
],
\"world\",
]",
format!("{:#?}", Bar)
format!("{Bar:#?}")
);
}
}
@ -668,13 +668,13 @@ fn test_formatting_parameters_are_forwarded() {
set.insert(1024);
set.insert(7);
assert_eq!(format!("{:03?}", struct_), "Foo { bar: 1024, baz: 007 }");
assert_eq!(format!("{:03?}", tuple), "(1024, 007)");
assert_eq!(format!("{:03?}", list), "[1024, 007]");
assert_eq!(format!("{:03?}", map), r#"{"bar": 1024, "baz": 007}"#);
assert_eq!(format!("{:03?}", set), "{007, 1024}");
assert_eq!(format!("{struct_:03?}"), "Foo { bar: 1024, baz: 007 }");
assert_eq!(format!("{tuple:03?}"), "(1024, 007)");
assert_eq!(format!("{list:03?}"), "[1024, 007]");
assert_eq!(format!("{map:03?}"), r#"{"bar": 1024, "baz": 007}"#);
assert_eq!(format!("{set:03?}"), "{007, 1024}");
assert_eq!(
format!("{:#03?}", struct_),
format!("{struct_:#03?}"),
"
Foo {
bar: 1024,
@ -684,7 +684,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", tuple),
format!("{tuple:#03?}"),
"
(
1024,
@ -694,7 +694,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", list),
format!("{list:#03?}"),
"
[
1024,
@ -704,7 +704,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", map),
format!("{map:#03?}"),
r#"
{
"bar": 1024,
@ -714,7 +714,7 @@ Foo {
.trim()
);
assert_eq!(
format!("{:#03?}", set),
format!("{set:#03?}"),
"
{
007,

View File

@ -6,7 +6,7 @@ mod num;
fn test_format_flags() {
// No residual flags left by pointer formatting
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");
}
@ -15,8 +15,8 @@ fn test_format_flags() {
fn test_pointer_formats_data_pointer() {
let b: &[u8] = b"";
let s: &str = "";
assert_eq!(format!("{:p}", s), format!("{:p}", s.as_ptr()));
assert_eq!(format!("{:p}", b), format!("{:p}", b.as_ptr()));
assert_eq!(format!("{s:p}"), format!("{:p}", s.as_ptr()));
assert_eq!(format!("{b:p}"), format!("{:p}", b.as_ptr()));
}
#[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() {
//test that float and integer match
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
assert_eq!(format!("{:.10e}", i8::MIN), "-1.2800000000e2");

View File

@ -113,7 +113,7 @@ fn aliasing_in_get() {
x.set(42).unwrap();
let at_x = x.get().unwrap(); // --- (shared) 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]

View File

@ -15,7 +15,7 @@ macro_rules! test_literal {
for input in inputs {
assert_eq!(input.parse(), Ok(x64));
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(-x32));
}
@ -123,9 +123,9 @@ fn inf() {
#[test]
fn massive_exponent() {
let max = i64::MAX;
assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e-{}000", max).parse(), Ok(0.0));
assert_eq!(format!("1e{}000", max).parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY));
assert_eq!(format!("1e-{max}000").parse(), Ok(0.0));
assert_eq!(format!("1e{max}000").parse(), Ok(f64::INFINITY));
}
#[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"101e-33"), Some(new_number(-33, 101)));
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)));
}

View File

@ -20,7 +20,7 @@ mod random;
pub fn decode_finite<T: DecodableFloat>(v: T) -> Decoded {
match decode(v).1 {
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 {
match decode(v).1 {
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.layout(), std::alloc::Layout::new::<Something>());
assert!(format!("{:?}", meta).starts_with("DynMetadata(0x"));
assert!(format!("{meta:?}").starts_with("DynMetadata(0x"));
}
#[test]

View File

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

View File

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

View File

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

View File

@ -83,7 +83,7 @@ pub use alloc_crate::alloc::*;
///
/// fn main() {
/// 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]";
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
assert_eq!(format!("{:#?}", backtrace), expected);
assert_eq!(format!("{backtrace:#?}"), expected);
}
#[test]
@ -91,5 +91,5 @@ fn test_frames() {
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"];
/// for &book in &to_find {
/// match book_reviews.get(book) {
/// Some(review) => println!("{}: {}", book, review),
/// None => println!("{} is unreviewed.", book)
/// Some(review) => println!("{book}: {review}"),
/// None => println!("{book} is unreviewed.")
/// }
/// }
///
@ -119,7 +119,7 @@ use crate::sys;
///
/// // Iterate over everything.
/// 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.
/// 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() {
/// println!("{}", key);
/// println!("{key}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -392,7 +392,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// ]);
///
/// for val in map.values() {
/// println!("{}", val);
/// println!("{val}");
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -419,7 +419,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// }
///
/// for val in map.values() {
/// println!("{}", val);
/// println!("{val}");
/// }
/// ```
#[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() {
/// println!("key: {} val: {}", key, val);
/// println!("key: {key} val: {val}");
/// }
/// ```
#[rustc_lint_query_instability]
@ -500,7 +500,7 @@ impl<K, V, S> HashMap<K, V, S> {
/// }
///
/// for (key, val) in &map {
/// println!("key: {} val: {}", key, val);
/// println!("key: {key} val: {val}");
/// }
/// ```
#[rustc_lint_query_instability]

View File

@ -515,10 +515,10 @@ fn test_show() {
map.insert(1, 2);
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_eq!(format!("{:?}", empty), "{}");
assert_eq!(format!("{empty:?}"), "{}");
}
#[test]
@ -702,7 +702,7 @@ fn test_entry_take_doesnt_corrupt() {
// Test for #19292
fn check(m: &HashMap<i32, ()>) {
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.
/// 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.
/// for x in &vikings {
/// println!("{:?}", x);
/// println!("{x:?}");
/// }
/// ```
///
@ -181,7 +181,7 @@ impl<T, S> HashSet<T, S> {
///
/// // Will print in an arbitrary order.
/// for x in set.iter() {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[inline]
@ -244,7 +244,7 @@ impl<T, S> HashSet<T, S> {
///
/// // print 1, 2, 3 in an arbitrary order
/// for i in set.drain() {
/// println!("{}", i);
/// println!("{i}");
/// }
///
/// assert!(set.is_empty());
@ -525,7 +525,7 @@ where
///
/// // Can be seen as `a - b`.
/// for x in a.difference(&b) {
/// println!("{}", x); // Print 1
/// println!("{x}"); // Print 1
/// }
///
/// let diff: HashSet<_> = a.difference(&b).collect();
@ -555,7 +555,7 @@ where
///
/// // Print 1, 4 in arbitrary order.
/// for x in a.symmetric_difference(&b) {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// let diff1: HashSet<_> = a.symmetric_difference(&b).collect();
@ -586,7 +586,7 @@ where
///
/// // Print 2, 3 in arbitrary order.
/// for x in a.intersection(&b) {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// let intersection: HashSet<_> = a.intersection(&b).collect();
@ -615,7 +615,7 @@ where
///
/// // Print 1, 2, 3, 4 in arbitrary order.
/// for x in a.union(&b) {
/// println!("{}", x);
/// println!("{x}");
/// }
///
/// 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.
/// for x in &v {
/// println!("{}", x);
/// println!("{x}");
/// }
/// ```
#[inline]

View File

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

View File

@ -199,7 +199,7 @@
//! ```
//! let vec = vec![1, 2, 3, 4];
//! for x in vec.iter() {
//! println!("vec contained {}", x);
//! println!("vec contained {x:?}");
//! }
//! ```
//!
@ -246,7 +246,7 @@
//! ```
//! let vec = vec![1, 2, 3, 4];
//! 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");
//! 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.
//! if person.blood_alcohol > 0.3 {
//! // Too drunk... for now.
//! println!("Sorry {}, I have to cut you off", id);
//! println!("Sorry {id}, I have to cut you off");
//! } else {
//! // Have another!
//! 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
/// // 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
/// // env::vars_os();
/// for (key, value) in env::vars_os() {
/// println!("{:?}: {:?}", key, value);
/// println!("{key:?}: {value:?}");
/// }
/// ```
#[must_use]
@ -212,8 +212,8 @@ impl fmt::Debug for VarsOs {
///
/// let key = "HOME";
/// match env::var(key) {
/// Ok(val) => println!("{}: {:?}", key, val),
/// Err(e) => println!("couldn't interpret {}: {}", key, e),
/// Ok(val) => println!("{key}: {val:?}"),
/// Err(e) => println!("couldn't interpret {key}: {e}"),
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]
@ -252,8 +252,8 @@ fn _var(key: &OsStr) -> Result<String, VarError> {
///
/// let key = "HOME";
/// match env::var_os(key) {
/// Some(val) => println!("{}: {:?}", key, val),
/// None => println!("{} is not defined in the environment.", key)
/// Some(val) => println!("{key}: {val:?}"),
/// None => println!("{key} is not defined in the environment.")
/// }
/// ```
#[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) {
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) {
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
@ -421,7 +421,7 @@ pub struct SplitPaths<'a> {
/// 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")]
@ -684,7 +684,7 @@ pub fn temp_dir() -> PathBuf {
/// match env::current_exe() {
/// Ok(exe_path) => println!("Path of this executable is: {}",
/// 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")]
@ -755,7 +755,7 @@ pub struct ArgsOs {
///
/// // Prints each argument on a separate line
/// for argument in env::args() {
/// println!("{}", argument);
/// println!("{argument}");
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]
@ -790,7 +790,7 @@ pub fn args() -> Args {
///
/// // Prints each argument on a separate line
/// for argument in env::args_os() {
/// println!("{:?}", argument);
/// println!("{argument:?}");
/// }
/// ```
#[stable(feature = "env", since = "1.0.0")]

View File

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

View File

@ -130,7 +130,7 @@ Stack backtrace:
error.backtrace = Some(trace);
let report = Report::new(error).pretty(true).show_backtrace(true);
println!("Error: {}", report);
println!("Error: {report}");
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 report = Report::new(error).pretty(true).show_backtrace(true);
println!("Error: {}", report);
println!("Error: {report}");
assert_eq!(expected.trim_end(), report.to_string());
}
@ -355,7 +355,7 @@ Caused by:
1: The message goes on and on.";
let actual = report.to_string();
println!("{}", actual);
println!("{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 {
f.write_str(self.description())?;
if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
write!(f, " at byte pos {}", pos)?;
write!(f, " at byte pos {pos}")?;
}
Ok(())
}
@ -1134,7 +1134,7 @@ impl fmt::Display for FromVecWithNulError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.error_kind {
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 => {
write!(f, "data provided is not nul terminated")

View File

@ -35,7 +35,7 @@ fn build_with_zero2() {
#[test]
fn formatted() {
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]

View File

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

View File

@ -30,7 +30,7 @@ macro_rules! check {
($e:expr) => {
match $e {
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));
let prefix = "foo";
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 msg_str = format!("{}{}", prefix, n.to_string());
let msg = msg_str.as_bytes();
@ -1329,7 +1329,7 @@ fn dir_entry_methods() {
assert!(file.file_type().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();
let mut read_dir = tmpdir.path().read_dir().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());
assert_eq!(actual, expected);
}
@ -1409,7 +1409,7 @@ fn metadata_access_times() {
|| e1.kind() == ErrorKind::Unsupported
&& e2.kind() == ErrorKind::Unsupported => {}
(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 len = reader.read_line(&mut line)?;
/// println!("First line is {} bytes long", len);
/// println!("First line is {len} bytes long");
/// Ok(())
/// }
/// ```

View File

@ -457,7 +457,7 @@ impl From<ErrorKind> for Error {
///
/// let not_found = ErrorKind::NotFound;
/// let error = Error::from(not_found);
/// assert_eq!("entity not found", format!("{}", error));
/// assert_eq!("entity not found", format!("{error}"));
/// ```
#[inline]
fn from(kind: ErrorKind) -> Error {
@ -561,7 +561,7 @@ impl Error {
/// use std::io::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")]
#[must_use]
@ -618,7 +618,7 @@ impl Error {
///
/// fn print_os_error(err: &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 {
/// println!("Not an OS error");
/// }
@ -657,7 +657,7 @@ impl Error {
///
/// fn print_error(err: &Error) {
/// if let Some(inner_err) = err.get_ref() {
/// println!("Inner error: {:?}", inner_err);
/// println!("Inner error: {inner_err:?}");
/// } else {
/// println!("No inner error");
/// }
@ -731,7 +731,7 @@ impl Error {
///
/// fn print_error(err: &Error) {
/// if let Some(inner_err) = err.get_ref() {
/// println!("Inner error: {}", inner_err);
/// println!("Inner error: {inner_err}");
/// } else {
/// println!("No inner error");
/// }
@ -770,7 +770,7 @@ impl Error {
///
/// fn print_error(err: Error) {
/// if let Some(inner_err) = err.into_inner() {
/// println!("Inner error: {}", inner_err);
/// println!("Inner error: {inner_err}");
/// } else {
/// println!("No inner error");
/// }
@ -852,7 +852,7 @@ impl fmt::Display for Error {
match self.repr.data() {
ErrorData::Os(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::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)
debug_assert!(
matches!(res.data(), ErrorData::Os(c) if c == code),
"repr(os) encoding failed for {}",
code,
"repr(os) encoding failed for {code}"
);
res
}

View File

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

View File

@ -91,7 +91,7 @@
//! // read a line into buffer
//! reader.read_line(&mut buffer)?;
//!
//! println!("{}", buffer);
//! println!("{buffer}");
//! Ok(())
//! }
//! ```
@ -1035,7 +1035,7 @@ pub trait Read {
/// fn main() -> io::Result<()> {
/// let stdin = io::read_to_string(io::stdin())?;
/// println!("Stdin was:");
/// println!("{}", stdin);
/// println!("{stdin}");
/// Ok(())
/// }
/// ```
@ -1761,7 +1761,7 @@ pub trait Seek {
/// .open("foo.txt").unwrap();
///
/// let hello = "Hello!\n";
/// write!(f, "{}", hello).unwrap();
/// write!(f, "{hello}").unwrap();
/// f.rewind().unwrap();
///
/// let mut buf = String::new();
@ -1804,7 +1804,7 @@ pub trait Seek {
/// let mut f = File::open("foo.txt")?;
///
/// let len = f.stream_len()?;
/// println!("The file is currently {} bytes long", len);
/// println!("The file is currently {len} bytes long");
/// Ok(())
/// }
/// ```
@ -1988,7 +1988,7 @@ pub trait BufRead: Read {
/// let buffer = stdin.fill_buf().unwrap();
///
/// // work with buffer
/// println!("{:?}", buffer);
/// println!("{buffer:?}");
///
/// // ensure the bytes we worked with aren't returned again later
/// let length = buffer.len();
@ -2042,7 +2042,7 @@ pub trait BufRead: Read {
/// let mut line = String::new();
/// stdin.read_line(&mut line).unwrap();
/// // work with line
/// println!("{:?}", line);
/// println!("{line:?}");
/// }
/// ```
#[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();
/// match io::stdin().read_line(&mut input) {
/// Ok(n) => {
/// println!("{} bytes read", n);
/// println!("{}", input);
/// println!("{n} bytes read");
/// 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) {
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);
/// println!("{}", last);
/// println!("{last}");
/// ```
///
/// A break expression is normally associated with the innermost loop enclosing the
@ -72,10 +72,10 @@ mod as_keyword {}
///
///```rust
/// 'outer: for i in 1..=5 {
/// println!("outer iteration (i): {}", i);
/// println!("outer iteration (i): {i}");
///
/// '_inner: for j in 1..=200 {
/// println!(" inner iteration (j): {}", j);
/// println!(" inner iteration (j): {j}");
/// if j >= 3 {
/// // breaks from inner loop, lets outer loop continue.
/// break;
@ -106,7 +106,7 @@ mod as_keyword {}
/// };
/// // first number in Fibonacci sequence over 10:
/// assert_eq!(result, 13);
/// println!("{}", result);
/// println!("{result}");
/// ```
///
/// 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 {
/// continue;
/// }
/// println!("{}", number);
/// println!("{number}");
/// }
///```
///
@ -515,7 +515,7 @@ mod fn_keyword {}
/// }
///
/// 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
/// }
///
@ -776,7 +776,7 @@ mod in_keyword {}
/// let shadowing_example = true;
/// let shadowing_example = 123.4;
/// 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
/// ```
///
@ -805,7 +805,7 @@ mod let_keyword {}
/// let mut counter = 0;
///
/// while counter < 10 {
/// println!("{}", counter);
/// println!("{counter}");
/// counter += 1;
/// }
/// ```
@ -836,7 +836,7 @@ mod let_keyword {}
/// if i == 10 {
/// counter = None;
/// } else {
/// println!("{}", i);
/// println!("{i}");
/// counter = Some (i + 1);
/// }
/// }
@ -866,7 +866,7 @@ mod while_keyword {}
///
/// let mut i = 1;
/// loop {
/// println!("i is {}", i);
/// println!("i is {i}");
/// if i > 100 {
/// break;
/// }
@ -920,8 +920,8 @@ mod loop_keyword {}
///
/// let a_number = Option::Some(10);
/// match a_number {
/// Some(x) if x <= 5 => println!("0 to 5 num = {}", x),
/// Some(x @ 6..=10) => println!("6 to 10 num = {}", x),
/// Some(x) if x <= 5 => println!("0 to 5 num = {x}"),
/// Some(x @ 6..=10) => println!("6 to 10 num = {x}"),
/// None => panic!(),
/// // all other numbers
/// _ => panic!(),
@ -940,8 +940,8 @@ mod loop_keyword {}
///
/// let get_inner = Outer::Double(None, Some(String::new()));
/// match get_inner {
/// Outer::Double(None, Some(st)) => println!("{}", st),
/// Outer::Single(opt) => println!("{:?}", opt),
/// Outer::Double(None, Some(st)) => println!("{st}"),
/// Outer::Single(opt) => println!("{opt:?}"),
/// _ => panic!(),
/// }
/// ```
@ -988,7 +988,7 @@ mod mod_keyword {}
///
/// ```rust
/// 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
/// ```
@ -1001,7 +1001,7 @@ mod mod_keyword {}
/// ```rust
/// fn create_fn() -> impl Fn() {
/// let text = "Fn".to_owned();
/// move || println!("This is a: {}", text)
/// move || println!("This is a: {text}")
/// }
///
/// let fn_plain = create_fn();
@ -1014,7 +1014,7 @@ mod mod_keyword {}
/// let data = vec![1, 2, 3];
///
/// std::thread::spawn(move || {
/// println!("captured {:?} by value", data)
/// println!("captured {data:?} by value")
/// }).join().unwrap();
///
/// // data was moved to the spawned thread, so we cannot use it here
@ -1025,7 +1025,7 @@ mod mod_keyword {}
/// ```rust
/// let capture = "hello".to_owned();
/// 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"));
/// // The variable 'maybe_name' is consumed here ...
/// match maybe_name {
/// Some(n) => println!("Hello, {}", n),
/// Some(n) => println!("Hello, {n}"),
/// _ => println!("Hello, world"),
/// }
/// // ... and is now unavailable.
@ -1138,7 +1138,7 @@ mod pub_keyword {}
/// let maybe_name = Some(String::from("Alice"));
/// // Using `ref`, the value is borrowed, not moved ...
/// match maybe_name {
/// Some(ref n) => println!("Hello, {}", n),
/// Some(ref n) => println!("Hello, {n}"),
/// _ => println!("Hello, world"),
/// }
/// // ... 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
/// assert_eq!(r1, r2);
/// // A static item can be used just like a variable in many cases
/// println!("{:?}", FOO);
/// println!("{FOO:?}");
/// ```
///
/// # Mutable `static`s
@ -1675,7 +1675,7 @@ mod super_keyword {}
/// # #![allow(dead_code)]
/// fn debug_iter<I: Iterator>(it: I) where I::Item: std::fmt::Debug {
/// for elem in it {
/// println!("{:#?}", elem);
/// println!("{elem:#?}");
/// }
/// }
///
@ -2313,7 +2313,7 @@ mod dyn_keyword {}
/// match u {
/// IntOrFloat { i: 10 } => println!("Found exactly ten!"),
/// // 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 };
///
/// *i = 10;
/// println!("f = {} and i = {}", f, i);
/// println!("f = {f} and i = {i}");
/// ```
///
/// See the [Reference][union] for more informations on `union`s.

View File

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

View File

@ -595,10 +595,10 @@ impl TcpStream {
/// // via platform-specific APIs such as epoll or IOCP
/// 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")]
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();
/// match listener.accept() {
/// Ok((_socket, addr)) => println!("new client: {:?}", addr),
/// Err(e) => println!("couldn't get client: {:?}", e),
/// Ok((_socket, addr)) => println!("new client: {addr:?}"),
/// Err(e) => println!("couldn't get client: {e:?}"),
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
@ -991,7 +991,7 @@ impl TcpListener {
/// wait_for_fd();
/// 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::BrokenPipe
|| e.kind() == ErrorKind::ConnectionAborted,
"unknown error: {}",
e
"unknown error: {e}"
);
}
}
@ -655,7 +654,7 @@ fn debug() {
inner_name,
render_inner(&listener)
);
assert_eq!(format!("{:?}", listener), compare);
assert_eq!(format!("{listener:?}"), compare);
let stream = t!(TcpStream::connect(&("localhost", socket_addr.port())));
let compare = format!(
@ -665,7 +664,7 @@ fn debug() {
inner_name,
render_inner(&stream)
);
assert_eq!(format!("{:?}", stream), compare);
assert_eq!(format!("{stream:?}"), compare);
}
// FIXME: re-enabled openbsd tests once their socket timeout code
@ -832,7 +831,7 @@ fn set_nonblocking() {
match stream.read(&mut buf) {
Ok(_) => panic!("expected error"),
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) {
Ok(_) => panic!("expected error"),
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => panic!("unexpected error {}", e),
Err(e) => panic!("unexpected error {e}"),
}
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");
/// match socket.take_error() {
/// Ok(Some(error)) => println!("UdpSocket error: {:?}", error),
/// Ok(Some(error)) => println!("UdpSocket error: {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")]
@ -686,8 +686,8 @@ impl UdpSocket {
/// socket.connect("127.0.0.1:8080").expect("connect function failed");
/// let mut buf = [0; 10];
/// match socket.recv(&mut buf) {
/// Ok(received) => println!("received {} bytes {:?}", received, &buf[..received]),
/// Err(e) => println!("recv function failed: {:?}", e),
/// Ok(received) => println!("received {received} bytes {:?}", &buf[..received]),
/// Err(e) => println!("recv function failed: {e:?}"),
/// }
/// ```
#[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");
/// let mut buf = [0; 10];
/// match socket.peek(&mut buf) {
/// Ok(received) => println!("received {} bytes", received),
/// Err(e) => println!("peek function failed: {:?}", e),
/// Ok(received) => println!("received {received} bytes"),
/// Err(e) => println!("peek function failed: {e:?}"),
/// }
/// ```
#[stable(feature = "peek", since = "1.18.0")]
@ -770,7 +770,7 @@ impl UdpSocket {
/// // via platform-specific APIs such as epoll or IOCP
/// wait_for_fd();
/// }
/// Err(e) => panic!("encountered IO error: {}", e),
/// Err(e) => panic!("encountered IO error: {e}"),
/// }
/// };
/// println!("bytes: {:?}", &buf[..num_bytes_read]);

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