【发布时间】:2021-02-25 21:24:08
【问题描述】:
作为一个在 Python 世界中安定下来的人,我最近不得不提高 API 的性能。出于个人兴趣,我想用 Golang 重做整个事情。
实现的一部分包括将坐标转换为 GeoJson 几何图形并从中创建一个集合。
由于某些端点需要从相同的坐标创建不同的几何图形,因此我想抽象出围绕构建几何图形的所有内容。我的方法是将返回接口实例的函数传递给转换坐标的方法。
// This is what I want to create
type Collection struct {
Geometries *[]Geometry
}
type Geometry interface {}
type Point struct {
Coordinates [1][2]float64
}
type Polygon struct {
Coordinates [1][5][2]float64
}
type GeometryConstructor func(float64, float64) *Geometry
// This is the method to convert
func DataFrameToCollection(data DataFrame, constructor GeometryConstructor) *Collection {
geometries := make([]Geometry, data.Len())
for i := 0; i < data.Len(); i++ {
geometries[i] = *constructor(data.Lat.ItemAt(i), data.Lng.ItemAt(i))
}
return &Collection{
Geometries: &geometries,
}
}
// This is a constructor method I want to pass
func PointFromLatLng(lat, lng float64) *Point {
return &Point{
Coordinates: [1][2]float64{
{lng, lat},
},
}
}
所以我最终可以像这样插入适当的构造方法
func main() {
// data := ...
collection := DataFrameToCollection(&data, PointFromLatLng)
}
问题在于构造方法没有返回接口实例。
解决这个问题的最惯用的方法是什么(避免 if / switch-case 语句)?
【问题讨论】:
标签: go inheritance interface