面试题答案
一键面试在Go语言中,若函数接收TypeA
类型参数,不能直接传入TypeB
类型的变量。这是因为Go语言是强类型语言,即使两个结构体的字段完全相同,但它们是不同的类型。
实现类似功能的办法:
- 类型转换(需要类型嵌入和方法集兼容):
可以通过类型嵌入和方法集的概念来实现某种程度的“转换”。假设
TypeA
和TypeB
都有相同的方法集,可在TypeB
中嵌入TypeA
,然后将TypeB
的实例转换为TypeA
的实例。
type TypeA struct {
Field1 string
Field2 int
}
type TypeB struct {
TypeA
}
func someFunction(a TypeA) {
// 函数逻辑
}
func main() {
b := TypeB{TypeA{"value1", 10}}
someFunction(b.TypeA)
}
- 使用接口:
定义一个接口,让
TypeA
和TypeB
都实现该接口,函数参数使用这个接口类型。
type CommonInterface interface {
SomeMethod()
}
type TypeA struct {
Field1 string
Field2 int
}
func (a TypeA) SomeMethod() {
// 方法实现
}
type TypeB struct {
Field1 string
Field2 int
}
func (b TypeB) SomeMethod() {
// 方法实现
}
func someFunction(i CommonInterface) {
// 函数逻辑
}
func main() {
a := TypeA{"value1", 10}
b := TypeB{"value1", 10}
someFunction(a)
someFunction(b)
}
- 编写转换函数:
手动编写一个转换函数,将
TypeB
转换为TypeA
。
type TypeA struct {
Field1 string
Field2 int
}
type TypeB struct {
Field1 string
Field2 int
}
func convertToTypeA(b TypeB) TypeA {
return TypeA{
Field1: b.Field1,
Field2: b.Field2,
}
}
func someFunction(a TypeA) {
// 函数逻辑
}
func main() {
b := TypeB{"value1", 10}
a := convertToTypeA(b)
someFunction(a)
}