aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/vlib/v/tests/generic_interface_test.v
blob: 059b1af7c72ba2f62015d358f66369aaece40b3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
interface Gettable<T> {
	get() T
}

struct Animal<T> {
	metadata T
}

fn (a Animal<T>) get<T>() T {
	return a.metadata
}

// different struct implementing the same interface:
struct Mineral<T> {
	value T
}

fn (m Mineral<T>) get<T>() T {
	return m.value
}

////

fn extract<T>(xs []Gettable<T>) []T {
	return xs.map(it.get())
}

fn extract_basic<T>(xs Gettable<T>) T {
	return xs.get()
}

fn test_extract() {
	a := Animal<int>{123}
	b := Animal<int>{456}
	c := Mineral<int>{789}

	arr := [Gettable<int>(a), Gettable<int>(b), Gettable<int>(c)]
	assert typeof(arr).name == '[]Gettable<int>'

	x := extract<int>(arr)
	assert x == [123, 456, 789]
}

// fn test_extract_multiple_instance_types() {
// 	a := Animal<string>{'123'}
// 	b := Animal<string>{'456'}
// 	c := Mineral<string>{'789'}

// 	arr := [Gettable<string>(a), Gettable<string>(b), Gettable<string>(c)]
// 	assert typeof(arr).name == '[]Gettable<string>'

// 	x := extract<string>(arr)
// 	assert x == ['123', '456', '789']
// }

fn test_extract_basic() {
	a := Animal<int>{123}
	b := Animal<int>{456}
	c := Mineral<int>{789}

	aa := extract_basic(a)
	bb := extract_basic(b)
	cc := extract_basic(c)
	assert '$aa | $bb | $cc' == '123 | 456 | 789'
}

//////
interface Iterator<T> {
	next() ?T
}

struct NumberIterator<T> {
	limit T
mut:
	val T
}

fn (mut i NumberIterator<T>) next<T>() ?T {
	if i.val >= i.limit {
		return none
	}
	i.val++
	return i.val
}

fn test_iterator_implementation() {
	mut i := Iterator<int>(NumberIterator<int>{
		limit: 10
	})
	for {
		if val := i.next() {
			println(val)
		} else {
			println('iterator is done')
			break
		}
	}
}