面试题答案
一键面试package main
import (
"fmt"
)
// 定义内部接口
type InnerInterface interface {
GetValue() int
}
// 定义外部接口
type OuterInterface interface {
GetInner() InnerInterface
}
// 实现外部接口的结构体
type OuterStruct struct{}
func (o OuterStruct) GetInner() InnerInterface {
// 这里简单返回一个匿名结构体实现的InnerInterface
return struct {
InnerInterface
}{
InnerInterface: struct {
GetValue func() int
}{
GetValue: func() int {
return 42
},
},
}
}
func main() {
var outer OuterInterface = OuterStruct{}
inner, ok := outer.GetInner().(InnerInterface)
if!ok {
fmt.Println("类型断言失败")
return
}
value := inner.GetValue()
fmt.Printf("获取到的值: %d\n", value)
}
上述代码中:
- 定义了
InnerInterface
接口,包含GetValue
方法返回int
类型值。 - 定义了
OuterInterface
接口,包含GetInner
方法返回InnerInterface
类型。 OuterStruct
结构体实现了OuterInterface
接口。- 在
main
函数中,通过类型断言获取InnerInterface
,并处理了类型断言失败的情况,成功获取后调用GetValue
方法并输出结果。