登录
首页 >  Golang >  Go问答

Golang 中用作参数传递的“抽象”构造函数技巧

来源:stackoverflow

时间:2024-03-18 10:09:30 256浏览 收藏

在 Go 语言中,需要抽象构造函数以用作参数传递时,可使用内联适配器。这可以避免使用 if/switch-case 语句,使代码更简洁。内联适配器将返回的类型转换为接口实例,从而允许构造函数传递给需要接口类型的方法。

问题内容

作为一个已经在 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 语句)?


解决方案


您可以使用内联适配器:

collection := DataFrameToCollection(&data, func(lat,lon float64) Geometry { return PointFromLatLng(lat,lon) } )

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>