Skip to content

Commit 0139836

Browse files
authored
tests: add more generic structs tests (#10095)
1 parent a9435f3 commit 0139836

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// test generics function that return generics struct
2+
pub struct Optional<T> {
3+
mut:
4+
value T
5+
some bool
6+
typ string
7+
}
8+
9+
pub fn new_some<T, B>(value T, b B) Optional<T> {
10+
return {
11+
value: value
12+
some: true
13+
typ: typeof(b).name
14+
}
15+
}
16+
17+
pub fn some<T>(opt Optional<T>) bool {
18+
return opt.some
19+
}
20+
21+
pub fn get_value<T>(opt Optional<T>) T {
22+
return opt.value
23+
}
24+
25+
pub fn get_typ<T>(opt Optional<T>) string {
26+
return opt.typ
27+
}
28+
29+
pub fn set<T, B>(mut opt Optional<T>, value T, b B) {
30+
opt.value = value
31+
opt.some = true
32+
opt.typ = typeof(b).name
33+
}
34+
35+
fn test_inconsistent_types_generics_fn_return_generics_struct() {
36+
mut o := new_some<int, string>(23, 'aaa')
37+
println(some<int>(o))
38+
assert some<int>(o) == true
39+
40+
println(get_value<int>(o))
41+
assert get_value<int>(o) == 23
42+
43+
set<int, string>(mut o, 42, 'aaa')
44+
println(get_value<int>(o))
45+
assert get_value<int>(o) == 42
46+
47+
println(get_typ<int>(o))
48+
assert get_typ<int>(o) == 'string'
49+
}
50+
51+
// test generics method that return generics struct
52+
pub struct Foo {
53+
foo int
54+
}
55+
56+
pub fn (f Foo) new_some<T, B>(value T, b B) Optional<T> {
57+
return {
58+
value: value
59+
some: true
60+
typ: typeof(b).name
61+
}
62+
}
63+
64+
pub fn (f Foo) some<T>(opt Optional<T>) bool {
65+
return opt.some
66+
}
67+
68+
pub fn (f Foo) get_value<T>(opt Optional<T>) T {
69+
return opt.value
70+
}
71+
72+
pub fn (f Foo) get_typ<T>(opt Optional<T>) string {
73+
return opt.typ
74+
}
75+
76+
pub fn (f Foo) set<T, B>(mut opt Optional<T>, value T, b B) {
77+
opt.value = value
78+
opt.some = true
79+
opt.typ = typeof(b).name
80+
}
81+
82+
fn test_inconstent_types_generics_method_return_generics_struct() {
83+
foo := Foo{}
84+
mut o := foo.new_some<int, string>(23, 'aaa')
85+
println(foo.some<int>(o))
86+
assert foo.some<int>(o) == true
87+
88+
println(foo.get_value<int>(o))
89+
assert foo.get_value<int>(o) == 23
90+
91+
foo.set<int, string>(mut o, 42, 'aaa')
92+
println(foo.get_value<int>(o))
93+
assert foo.get_value<int>(o) == 42
94+
95+
println(foo.get_typ<int>(o))
96+
assert foo.get_typ<int>(o) == 'string'
97+
}

0 commit comments

Comments
 (0)