Go类型转换错误Cannot convert an expression of the type 'interface{}' to the type 'XXX'

1、问题引出

在编码中经常会涉及到类型转换的问题,在Go语言中也是一样的,一次在开发中将interface{}类型强制转换成具体类型时,出现了如下错误:

1
Cannot convert an expression of the type 'interface{}' to the type 'Person'

为了引出该问题,在此先引入3个结构体,即:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Person结构体
type Person struct {
Name string
Age int
}

// Student结构体
type Student struct {
Name string
Age int
}

// Obj结构体
type Obj struct {
ID int
Type interface{}
}

创建一个person对象和obj对象:

1
2
3
4
5
6
7
8
9
person := Person{
Name: "lzj",
Age: 20,
}

obj := Obj{
ID: 1,
Type: person,
}

由于Student结构体与Person结构体中的字段和类型都是一样的,其实是可以将person对象强制转换成student对象的,即:

1
2
student := Student(person)
fmt.Printf("Student: Name: %v, Age: %v\n", student.Name, student.Age)

这里是可以成功的,而且输出结果为:

1
Student: Name: lzj, Age: 20

如果将obj对象中的Type属性值转换Person结构体对象,也是按照以上的这种强制转换的话,就会有问题,即:

1
2
p := Person(obj.Type)
// 该代码会报错:Cannot convert an expression of the type 'interface{}' to the type 'Person'

2、解决办法

interface{}转换成其它类型,所用的方式为:

1
结果 := interface类型.(转换的类型)

所以上述的转换需要改成:

1
2
p := obj.Type.(Person)
fmt.Printf("Person: Name: %v, Age: %v\n", p.Name, p.Age)

这样就可以转换成功,并输入结果为:

1
Person: Name: lzj, Age: 20

Go类型转换错误Cannot convert an expression of the type 'interface{}' to the type 'XXX'

https://lzj09.github.io/2021/04/17/go-convert-type-error/

作者

lzj09

发布于

2021-04-17

更新于

2021-04-17

许可协议

评论