面试题答案
一键面试- 识别动态类型的方法:
- 在Go语言中,可以使用类型断言(Type Assertion)来识别接口变量中存储的动态类型。类型断言的语法为
x.(T)
,其中x
是接口类型的变量,T
是要断言的类型。如果x
实际存储的动态类型是T
,则类型断言成功,返回动态值和一个布尔值true
;如果断言失败,返回零值和false
。 - 还可以使用
switch
语句结合类型断言(type switch
)来更灵活地处理多种类型的断言。
- 在Go语言中,可以使用类型断言(Type Assertion)来识别接口变量中存储的动态类型。类型断言的语法为
- 示例代码:
package main
import (
"fmt"
)
// 定义一个接口
type MyInterface interface {
DoSomething()
}
// 定义两个结构体类型,实现MyInterface接口
type StructA struct{}
func (sa StructA) DoSomething() {
fmt.Println("StructA DoSomething")
}
type StructB struct{}
func (sb StructB) DoSomething() {
fmt.Println("StructB DoSomething")
}
func main() {
// 定义一个接口类型的变量,并赋值不同的动态类型
var i MyInterface
i = StructA{}
// 使用类型断言识别动态类型
if sa, ok := i.(StructA); ok {
fmt.Printf("动态类型是StructA,值为: %v\n", sa)
} else if sb, ok := i.(StructB); ok {
fmt.Printf("动态类型是StructB,值为: %v\n", sb)
} else {
fmt.Println("未知的动态类型")
}
// 使用type switch识别动态类型
switch v := i.(type) {
case StructA:
fmt.Printf("通过type switch识别,动态类型是StructA,值为: %v\n", v)
case StructB:
fmt.Printf("通过type switch识别,动态类型是StructB,值为: %v\n", v)
default:
fmt.Println("通过type switch识别,未知的动态类型")
}
}
在上述代码中:
- 首先定义了一个接口
MyInterface
以及两个实现该接口的结构体StructA
和StructB
。 - 在
main
函数中,给接口变量i
赋予了StructA
类型的值。 - 然后通过类型断言的两种方式(
if - else
和type switch
)来识别接口变量i
中存储的动态类型。