【发布时间】:2022-06-10 20:51:45
【问题描述】:
如何通过静态分析判断变量的类型?
假设我有以下代码:
func doSomething(x interface{}) {}
func main() {
p := Person()
doSomething(p)
}
而我要分析doSomething(person),是否可以通过静态分析得到Person的类型?
如果有多个级别的分配怎么办?
p1 := Person()
p2 := p1
doSomething(p2)
或
parent := Parent()
p := Parent.Child() // type Person
doSomething(p)
用例是我有一个在整个(非常大的)代码库中常用的通用函数,并且想介绍这个函数的新类型安全版本。为此,我希望自动确定函数的“类型”并相应地对其进行重构:
// old
DB.InsertRow(person)
// new
Person.InsertRow(person)
【问题讨论】:
-
如果
Person()返回一个具体类型,是的,可以得到p1、p2、parent和p的类型(假设Parent.Child()也返回具体类型)。但是,如果函数返回一个接口,其动态类型是根据程序在运行时获取的一些参数(例如用户输入、来自数据库或互联网等)决定的,那么静态分析将不足以获取类型. -
如果将其作为赏金 - 在此处为您的更大目标添加更多清晰度可能会有所帮助。
标签: go types static-analysis