MST

星途 面试题库

面试题:Go语言类型断言在接口嵌套中的应用

定义一个接口 `OuterInterface`,其中包含一个方法 `GetInner()`,该方法返回另一个接口 `InnerInterface`。`InnerInterface` 有一个方法 `GetValue()` 返回 `int`。现有一个实现了 `OuterInterface` 的结构体 `OuterStruct`。请写一段代码,通过类型断言从 `OuterInterface` 类型的变量获取到 `InnerInterface` 并调用 `GetValue()` 方法,同时处理可能出现的类型断言错误。
38.9万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
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)
}

上述代码中:

  1. 定义了 InnerInterface 接口,包含 GetValue 方法返回 int 类型值。
  2. 定义了 OuterInterface 接口,包含 GetInner 方法返回 InnerInterface 类型。
  3. OuterStruct 结构体实现了 OuterInterface 接口。
  4. main 函数中,通过类型断言获取 InnerInterface,并处理了类型断言失败的情况,成功获取后调用 GetValue 方法并输出结果。