github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/compiler/testdata/interface.go (about) 1 // This file tests interface types and interface builtins. 2 3 package main 4 5 // Test interface construction. 6 7 func simpleType() interface{} { 8 return 0 9 } 10 11 func pointerType() interface{} { 12 // Pointers have an element type, in this case int. 13 var v *int 14 return v 15 } 16 17 func interfaceType() interface{} { 18 // Interfaces can exist in interfaces, but only indirectly (through 19 // pointers). 20 var v *error 21 return v 22 } 23 24 func anonymousInterfaceType() interface{} { 25 var v *interface { 26 String() string 27 } 28 return v 29 } 30 31 // Test interface builtins. 32 33 func isInt(itf interface{}) bool { 34 _, ok := itf.(int) 35 return ok 36 } 37 38 func isError(itf interface{}) bool { 39 // Interface assert on (builtin) named interface type. 40 _, ok := itf.(error) 41 return ok 42 } 43 44 func isStringer(itf interface{}) bool { 45 // Interface assert on anonymous interface type. 46 _, ok := itf.(interface { 47 String() string 48 }) 49 return ok 50 } 51 52 type fooInterface interface { 53 String() string 54 foo(int) byte 55 } 56 57 func callFooMethod(itf fooInterface) uint8 { 58 return itf.foo(3) 59 } 60 61 func callErrorMethod(itf error) string { 62 return itf.Error() 63 }