]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/tuple-struct-self-ctor.rs
implement feature tuple_struct_self_ctor
[rust.git] / src / test / run-pass / tuple-struct-self-ctor.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![feature(tuple_struct_self_ctor)]
12
13 #![allow(dead_code)]
14
15 use std::fmt::Display;
16
17 struct ST1(i32, i32);
18
19 impl ST1 {
20     fn new() -> Self {
21         ST1(0, 1)
22     }
23
24     fn ctor() -> Self {
25         Self(1,2)         // Self as a constructor
26     }
27
28     fn pattern(self) {
29         match self {
30             Self(x, y) => println!("{} {}", x, y), // Self as a pattern
31         }
32     }
33 }
34
35 struct ST2<T>(T); // With type parameter
36
37 impl<T> ST2<T> where T: Display {
38
39     fn ctor(v: T) -> Self {
40         Self(v)
41     }
42
43     fn pattern(&self) {
44         match self {
45             Self(ref v) => println!("{}", v),
46         }
47     }
48 }
49
50 struct ST3<'a>(&'a i32); // With lifetime parameter
51
52 impl<'a> ST3<'a> {
53
54     fn ctor(v: &'a i32) -> Self {
55         Self(v)
56     }
57
58     fn pattern(self) {
59         let Self(ref v) = self;
60         println!("{}", v);
61     }
62 }
63
64 struct ST4(usize);
65
66 impl ST4 {
67     fn map(opt: Option<usize>) -> Option<Self> {
68         opt.map(Self)     // use `Self` as a function passed somewhere
69     }
70 }
71
72 struct ST5;               // unit struct
73
74 impl ST5 {
75     fn ctor() -> Self {
76         Self               // `Self` as a unit struct value
77     }
78
79     fn pattern(self) -> Self {
80         match self {
81             Self => Self,   // `Self` as a unit struct value for matching
82         }
83     }
84 }
85
86 fn main() {
87     let v1 = ST1::ctor();
88     v1.pattern();
89
90     let v2 = ST2::ctor(10);
91     v2.pattern();
92
93     let local = 42;
94     let v3 = ST3::ctor(&local);
95     v3.pattern();
96
97     let v4 = Some(1usize);
98     let _ = ST4::map(v4);
99
100     let v5 = ST5::ctor();
101     v5.pattern();
102 }