v2 / vlib / v / tests / interfaces / interface_embedding_smartcast_test.v
47 lines · 41 sloc · 729 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1// Common interface to all error custom types.
2interface ESpeaker {
3 IError
4 speak() string
5}
6
7// One custom error implementation.
8struct 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.
17fn (e MyError) speak() string {
18 return e.blah
19}
20
21fn (e MyError) msg() string {
22 return e.msg
23}
24
25fn (e MyError) code() int {
26 return e.code
27}
28
29// An example function that returns a custom error.
30fn foo() !string {
31 return MyError{
32 msg: 'foo'
33 blah: 'world'
34 }
35}
36
37fn 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