]> git.lizzy.rs Git - rust.git/blob - src/test/ui/fmt/format-args-capture.rs
Add `format_args_capture` feature
[rust.git] / src / test / ui / fmt / format-args-capture.rs
1 // run-pass
2 #![feature(format_args_capture)]
3
4 fn main() {
5     named_argument_takes_precedence_to_captured();
6     panic_with_single_argument_does_not_get_formatted();
7     panic_with_multiple_arguments_is_formatted();
8     formatting_parameters_can_be_captured();
9 }
10
11 fn named_argument_takes_precedence_to_captured() {
12     let foo = "captured";
13     let s = format!("{foo}", foo="named");
14     assert_eq!(&s, "named");
15
16     let s = format!("{foo}-{foo}-{foo}", foo="named");
17     assert_eq!(&s, "named-named-named");
18
19     let s = format!("{}-{bar}-{foo}", "positional", bar="named");
20     assert_eq!(&s, "positional-named-captured");
21 }
22
23 fn panic_with_single_argument_does_not_get_formatted() {
24     // panic! with a single argument does not perform string formatting.
25     // RFC #2795 suggests that this may need to change so that captured arguments are formatted.
26     // For stability reasons this will need to part of an edition change.
27
28     let msg = std::panic::catch_unwind(|| {
29         panic!("{foo}");
30     }).unwrap_err();
31
32     assert_eq!(msg.downcast_ref::<&str>(), Some(&"{foo}"))
33 }
34
35 fn panic_with_multiple_arguments_is_formatted() {
36     let foo = "captured";
37
38     let msg = std::panic::catch_unwind(|| {
39         panic!("{}-{bar}-{foo}", "positional", bar="named");
40     }).unwrap_err();
41
42     assert_eq!(msg.downcast_ref::<String>(), Some(&"positional-named-captured".to_string()))
43 }
44
45 fn formatting_parameters_can_be_captured() {
46     let width = 9;
47     let precision = 3;
48
49     let x = 7.0;
50
51     let s = format!("{x:width$}");
52     assert_eq!(&s, "        7");
53
54     let s = format!("{x:<width$}");
55     assert_eq!(&s, "7        ");
56
57     let s = format!("{x:-^width$}");
58     assert_eq!(&s, "----7----");
59
60     let s = format!("{x:-^width$.precision$}");
61     assert_eq!(&s, "--7.000--");
62 }