| 1 | fn get_opt(a int) ?string { |
| 2 | if a < 0 { |
| 3 | return none |
| 4 | } |
| 5 | return 'success' |
| 6 | } |
| 7 | |
| 8 | fn get_opt_int(a int) ?int { |
| 9 | if a < 0 { |
| 10 | return none |
| 11 | } |
| 12 | return 12 |
| 13 | } |
| 14 | |
| 15 | struct TestResult { |
| 16 | cols map[string]int |
| 17 | rows []TestRow |
| 18 | } |
| 19 | |
| 20 | struct TestRow { |
| 21 | vals []?string |
| 22 | } |
| 23 | |
| 24 | struct TestDb {} |
| 25 | |
| 26 | struct TestPgConnection { |
| 27 | db TestDb |
| 28 | } |
| 29 | |
| 30 | fn (db TestDb) exec_result(_ string) !TestResult { |
| 31 | return TestResult{ |
| 32 | cols: { |
| 33 | 'present': 0 |
| 34 | 'empty': 1 |
| 35 | 'none': 2 |
| 36 | } |
| 37 | rows: [TestRow{ |
| 38 | vals: [?string('hello'), ?string(''), ?string(none)] |
| 39 | }] |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | fn (c &TestPgConnection) query(q string) ![]map[string]string { |
| 44 | res := c.db.exec_result(q)! |
| 45 | mut rows := []map[string]string{} |
| 46 | |
| 47 | for row in res.rows { |
| 48 | mut values := map[string]string{} |
| 49 | for col, idx in res.cols { |
| 50 | values[col] = row.vals[idx] or { '' } as string |
| 51 | } |
| 52 | rows << values |
| 53 | } |
| 54 | return rows |
| 55 | } |
| 56 | |
| 57 | fn test_option_unwrap_as_cast() { |
| 58 | x := get_opt(1) |
| 59 | d := get_opt_int(12) |
| 60 | dump(d? as int == 12) |
| 61 | dump('${x? as string}' == 'success') |
| 62 | |
| 63 | assert d? as int == 12 |
| 64 | assert x? as string == 'success' |
| 65 | } |
| 66 | |
| 67 | fn test_option_array_index_or_block_followed_by_as_cast() { |
| 68 | conn := &TestPgConnection{ |
| 69 | db: TestDb{} |
| 70 | } |
| 71 | rows := conn.query('select') or { panic(err) } |
| 72 | |
| 73 | assert rows.len == 1 |
| 74 | assert rows[0]['present'] == 'hello' |
| 75 | assert rows[0]['empty'] == '' |
| 76 | assert rows[0]['none'] == '' |
| 77 | } |
| 78 | |