| 1 | // Common interface to all error custom types. |
| 2 | interface ESpeaker { |
| 3 | IError |
| 4 | speak() string |
| 5 | } |
| 6 | |
| 7 | // One custom error implementation. |
| 8 | struct MyError { |
| 9 | // Mandatory fields from IError. |
| 10 | msg string |
| 11 | code int |
| 12 | // Custom field. |
| 13 | blah string |
| 14 | } |
| 15 | |
| 16 | // Interface implementation for this example custom type. |
| 17 | fn (e MyError) speak() string { |
| 18 | return e.blah |
| 19 | } |
| 20 | |
| 21 | fn (e MyError) msg() string { |
| 22 | return e.msg |
| 23 | } |
| 24 | |
| 25 | fn (e MyError) code() int { |
| 26 | return e.code |
| 27 | } |
| 28 | |
| 29 | // An example function that returns a custom error. |
| 30 | fn foo() !string { |
| 31 | return MyError{ |
| 32 | msg: 'foo' |
| 33 | blah: 'world' |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | fn test_interface_embedding_smartcast() { |
| 38 | x := foo() or { |
| 39 | if err is ESpeaker { |
| 40 | err.speak() |
| 41 | } else { |
| 42 | 'undefined' |
| 43 | } |
| 44 | } |
| 45 | println(x) |
| 46 | assert x == 'world' |
| 47 | } |
| 48 | |