| 1 | module main |
| 2 | |
| 3 | interface Point { |
| 4 | coords() (int, int) |
| 5 | } |
| 6 | |
| 7 | struct SPoint { |
| 8 | x int |
| 9 | y int |
| 10 | } |
| 11 | |
| 12 | fn (s SPoint) coords() (int, int) { |
| 13 | return s.x, s.y |
| 14 | } |
| 15 | |
| 16 | fn new_spoints() []SPoint { |
| 17 | return [ |
| 18 | SPoint{10, 10}, |
| 19 | SPoint{15, 11}, |
| 20 | SPoint{1, 22}, |
| 21 | ] |
| 22 | } |
| 23 | |
| 24 | fn 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 | |
| 33 | fn test_pass_array_of_structs_to_array_of_interface_param() { |
| 34 | spoints := new_spoints() |
| 35 | assert sum_x(spoints) == 26 |
| 36 | } |
| 37 | |
| 38 | fn 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 | |
| 45 | interface Cols { |
| 46 | cols() string |
| 47 | } |
| 48 | |
| 49 | struct Data implements Cols {} |
| 50 | |
| 51 | fn (d Data) cols() string { |
| 52 | return 'data' |
| 53 | } |
| 54 | |
| 55 | fn print_first_last(cols []Cols) string { |
| 56 | return '${cols[0].cols()}:${cols[cols.len - 1].cols()}' |
| 57 | } |
| 58 | |
| 59 | fn 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 | |
| 64 | fn 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 | |