简体   繁体   English

在 Golang 中将基类型转换为派生类型

[英]Casting base type to derived type in Golang

I'm not entirely sure how to ask this question - I have a type that I 'derived' from another using the standard golang type keyword:我不完全确定如何问这个问题 - 我有一个类型,我使用标准的 golang 类型关键字从另一个类型“派生”:

type EWKBGeomPoint geom.Point

I want to essentially 'override' the geom.Point Scan() and Value() functions, so I have the following function:我想基本上“覆盖” geom.Point Scan() 和 Value() 函数,所以我有以下函数:

func (g *EWKBGeomPoint) Scan(input interface{}) error {
    gt, err := ewkbhex.Decode(string(input.([]byte)))
    if err != nil {
        return err
    }
    g = gt.(*geom.Point) // error here

    return nil
}

However, when I run this, it has an interface conversion error:但是,当我运行它时,它有一个接口转换错误:

interface conversion: geom.T is *geom.Point, not *models.EWKBGeomPoint

I don't understand why this is the case - I have seen multiple code samples now that allow this behavior.我不明白为什么会这样 - 我现在已经看到多个允许这种行为的代码示例。 Also it would intuitively seem to me that it should work, because they are basically the same types with all of the same underlying variables and functions.此外,在我看来,它应该可以工作,因为它们基本上是相同的类型,具有所有相同的底层变量和函数。

How can I convert this type to the target type?如何将此类型转换为目标类型?

Link to go-geom docs 链接到 go-geom 文档

Go version is go1.13.4 linux/amd64 Go 版本是 go1.13.4 linux/amd64

You cannot override functions in Go.你不能在 Go 中覆盖函数。

If you define a new type like:如果您定义了一个新类型,例如:

type EWKBGeomPoint geom.Point

Then EWKBGeomPoint is a new type containing the same member fields of geom.Point , but none of its methods.那么EWKBGeomPoint是一个新类型,包含与geom.Point相同的成员字段,但没有它的方法。

If you define a new type by embedding:如果您通过嵌入来定义新类型:

type EWKBGeomPoint struct {
   geom.Point
}

Then, EWKBGeomPoint is a new type embedding a geom.Point .然后, EWKBGeomPoint是一种嵌入geom.Point的新类型。 All member variables and functions of geom.Point are also defined for EWKBGeomPoint . geom.Point所有成员变量和函数也是为EWKBGeomPoint定义的。

If you use your declaration, you can convert the result:如果使用声明,则可以转换结果:

g = (*models.EWKBGeomPoint)(gt.(*geom.Point))

If you use type embedding, you can assign it to the embedded point:如果使用类型嵌入,则可以将其分配给嵌入点:

g.Point = *gt.(*geom.Point)

However, either case you did not override the Scan function, you defined a Scan function for the new type.但是,无论哪种情况,您都没有覆盖Scan函数,而是为新类型定义了Scan函数。

您只能输入 assert接口中的内容,因此您别无选择,只能使用gt.(*geom.Point) ,但您可以转换结果:

g = (*models.EWKBGeomPoint)(gt.(*geom.Point))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM