面试题答案
一键面试设计方案
- 定义空接口:使用空接口
interface{}
来接收不同结构的数据。 - 数据类型断言:在处理函数中,通过类型断言判断数据实际类型,进行相应处理。
- 标准化处理:根据不同类型数据,转换为统一格式。
- 输出统一格式数据:将处理后的数据输出。
关键代码实现(以Go语言为例)
package main
import (
"fmt"
)
// 定义统一输出的数据结构
type StandardData struct {
Key string
Value interface{}
}
// 通用数据处理函数
func processData(data interface{}) StandardData {
var stdData StandardData
switch data := data.(type) {
case int:
stdData.Key = "intValue"
stdData.Value = data
case string:
stdData.Key = "stringValue"
stdData.Value = data
default:
stdData.Key = "unknownType"
stdData.Value = data
}
return stdData
}
可以通过以下方式调用该函数:
func main() {
intData := 10
stringData := "hello"
intResult := processData(intData)
stringResult := processData(stringData)
fmt.Println(intResult)
fmt.Println(stringResult)
}