github.com/goplus/igop@v0.25.0/testdata/ifaceconv.go (about) 1 package main 2 3 // Tests of interface conversions and type assertions. 4 5 type I0 interface { 6 } 7 type I1 interface { 8 f() 9 } 10 type I2 interface { 11 f() 12 g() 13 } 14 15 type C0 struct{} 16 type C1 struct{} 17 18 func (C1) f() {} 19 20 type C2 struct{} 21 22 func (C2) f() {} 23 func (C2) g() {} 24 25 func main() { 26 var i0 I0 27 var i1 I1 28 var i2 I2 29 30 // Nil always causes a type assertion to fail, even to the 31 // same type. 32 if _, ok := i0.(I0); ok { 33 panic("nil i0.(I0) succeeded") 34 } 35 if _, ok := i1.(I1); ok { 36 panic("nil i1.(I1) succeeded") 37 } 38 if _, ok := i2.(I2); ok { 39 panic("nil i2.(I2) succeeded") 40 } 41 42 // Conversions can't fail, even with nil. 43 _ = I0(i0) 44 45 _ = I0(i1) 46 _ = I1(i1) 47 48 _ = I0(i2) 49 _ = I1(i2) 50 _ = I2(i2) 51 52 // Non-nil type assertions pass or fail based on the concrete type. 53 i1 = C1{} 54 if _, ok := i1.(I0); !ok { 55 panic("C1 i1.(I0) failed") 56 } 57 if _, ok := i1.(I1); !ok { 58 panic("C1 i1.(I1) failed") 59 } 60 if _, ok := i1.(I2); ok { 61 panic("C1 i1.(I2) succeeded") 62 } 63 64 i1 = C2{} 65 if _, ok := i1.(I0); !ok { 66 panic("C2 i1.(I0) failed") 67 } 68 if _, ok := i1.(I1); !ok { 69 panic("C2 i1.(I1) failed") 70 } 71 if _, ok := i1.(I2); !ok { 72 panic("C2 i1.(I2) failed") 73 } 74 75 // Conversions can't fail. 76 i1 = C1{} 77 if I0(i1) == nil { 78 panic("C1 I0(i1) was nil") 79 } 80 if I1(i1) == nil { 81 panic("C1 I1(i1) was nil") 82 } 83 }