]> git.proxmox.com Git - rustc.git/blob - tests/ui/rfcs/rfc-2302-self-struct-ctor.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / tests / ui / rfcs / rfc-2302-self-struct-ctor.rs
1 // run-pass
2
3 #![allow(dead_code)]
4
5 use std::fmt::Display;
6
7 struct ST1(i32, i32);
8
9 impl ST1 {
10 fn new() -> Self {
11 ST1(0, 1)
12 }
13
14 fn ctor() -> Self {
15 Self(1,2) // Self as a constructor
16 }
17
18 fn pattern(self) {
19 match self {
20 Self(x, y) => println!("{} {}", x, y), // Self as a pattern
21 }
22 }
23 }
24
25 struct ST2<T>(T); // With type parameter
26
27 impl<T> ST2<T> where T: Display {
28
29 fn ctor(v: T) -> Self {
30 Self(v)
31 }
32
33 fn pattern(&self) {
34 match self {
35 Self(ref v) => println!("{}", v),
36 }
37 }
38 }
39
40 struct ST3<'a>(&'a i32); // With lifetime parameter
41
42 impl<'a> ST3<'a> {
43
44 fn ctor(v: &'a i32) -> Self {
45 Self(v)
46 }
47
48 fn pattern(self) {
49 let Self(ref v) = self;
50 println!("{}", v);
51 }
52 }
53
54 struct ST4(usize);
55
56 impl ST4 {
57 fn map(opt: Option<usize>) -> Option<Self> {
58 opt.map(Self) // use `Self` as a function passed somewhere
59 }
60 }
61
62 struct ST5; // unit struct
63
64 impl ST5 {
65 fn ctor() -> Self {
66 Self // `Self` as a unit struct value
67 }
68
69 fn pattern(self) -> Self {
70 match self {
71 Self => Self, // `Self` as a unit struct value for matching
72 }
73 }
74 }
75
76 struct ST6(i32);
77 type T = ST6;
78 impl T {
79 fn ctor() -> Self {
80 ST6(1)
81 }
82
83 fn type_alias(self) {
84 let Self(_x) = match self { Self(x) => Self(x) };
85 let _opt: Option<Self> = Some(0).map(Self);
86 }
87 }
88
89 struct ST7<T1, T2>(T1, T2);
90
91 impl ST7<i32, usize> {
92
93 fn ctor() -> Self {
94 Self(1, 2)
95 }
96
97 fn pattern(self) -> Self {
98 match self {
99 Self(x, y) => Self(x, y),
100 }
101 }
102 }
103
104 fn main() {
105 let v1 = ST1::ctor();
106 v1.pattern();
107
108 let v2 = ST2::ctor(10);
109 v2.pattern();
110
111 let local = 42;
112 let v3 = ST3::ctor(&local);
113 v3.pattern();
114
115 let v4 = Some(1usize);
116 let _ = ST4::map(v4);
117
118 let v5 = ST5::ctor();
119 v5.pattern();
120
121 let v6 = ST6::ctor();
122 v6.type_alias();
123
124 let v7 = ST7::<i32, usize>::ctor();
125 let r = v7.pattern();
126 println!("{} {}", r.0, r.1)
127 }