Files
wa/waroot/examples/interface_named.wa

90 lines
1.4 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 版权 @2021 凹语言 作者。保留所有权利。
type T1 :struct {
a: i32
}
type T2 :struct {
b: i32
}
type I1 :interface {
f()
}
type I2 :interface {
f2()
}
func T1.f {
println("This is T1, this.a==", this.a)
}
func T2.f {
println("This is T2, this.b==", this.b)
}
func main {
v1 := T1{a: 13}
i1: I1 = &v1 //具体类型到具名接口
v1.f() //直接调用
i1.f() //接口调用
doConcreteType(i1)
i1.f()
v2 := T2{b: 42}
i1 = &v2 //具体类型到具名接口
i1.f()
doConcreteType(i1)
i1.f()
ni: interface{} = &v1 //具体类型到空接口
i1 = ni.(I1) //接口动态互转
i1.f()
ni = &v2 //具体类型到空接口
i1 = ni.(I1) //接口动态互转
i1.f()
ival: i32 = 777
ni = ival
doConcreteType(ni)
doConcreteType(v1)
doConcreteType(v2)
doConcreteType("你好凹语言")
//i2 := ni.(I2) //接口互转由于v2未实现I2这会触发异常
//i2.f2()
anoni: interface{ f() } = &v1 //具体类型到匿名接口
anoni.f()
i1 = anoni //匿名接口向具名接口转换
i1.f()
}
func doConcreteType(i: interface{}) {
//接口到具体类型断言
switch c := i.(type) {
case *T1:
println("*T1")
c.a *= 2
case *T2:
println("*T2")
c.b *= 2
case i32:
println("i32: ", c)
case string:
println("string: ", c)
case T1:
println("T1, T1.a==", c.a)
case T2:
println("T2, T2.b==", c.b)
}
}