v2 / vlib / v / tests / interfaces / interface_array_implicit_conversion_test.v
67 lines · 54 sloc · 1.15 KB · 537d99439dc77530d717b23806447b178d63901a
Raw
1module main
2
3interface Point {
4 coords() (int, int)
5}
6
7struct SPoint {
8 x int
9 y int
10}
11
12fn (s SPoint) coords() (int, int) {
13 return s.x, s.y
14}
15
16fn new_spoints() []SPoint {
17 return [
18 SPoint{10, 10},
19 SPoint{15, 11},
20 SPoint{1, 22},
21 ]
22}
23
24fn sum_x(points []Point) int {
25 mut total := 0
26 for point in points {
27 x, _ := point.coords()
28 total += x
29 }
30 return total
31}
32
33fn test_pass_array_of_structs_to_array_of_interface_param() {
34 spoints := new_spoints()
35 assert sum_x(spoints) == 26
36}
37
38fn test_append_array_of_structs_to_array_of_interface() {
39 spoints := new_spoints()
40 mut points := []Point{}
41 points << spoints
42 assert sum_x(points) == 26
43}
44
45interface Cols {
46 cols() string
47}
48
49struct Data implements Cols {}
50
51fn (d Data) cols() string {
52 return 'data'
53}
54
55fn print_first_last(cols []Cols) string {
56 return '${cols[0].cols()}:${cols[cols.len - 1].cols()}'
57}
58
59fn test_pass_len_initialized_array_of_implements_struct_to_array_of_interface_param() {
60 data := []Data{len: 3}
61 assert print_first_last(data) == 'data:data'
62}
63
64fn test_pass_array_of_struct_pointers_to_array_of_interface_param() {
65 data := []&Data{len: 3, init: &Data{}}
66 assert print_first_last(data) == 'data:data'
67}
68