从Go lang中的同一函数返回不同的接口专用实现

Har*_*rel 4 interface go

我有一些数据结构,每个数据结构都有一些独特的字段.它们都实现了相同的行为接口(DataPoint).因此,他们的处理可以在交换每个结构的类型并通过界面中定义的方法对其进行操作时完成一次.我希望有一个函数根据某些条件返回每种类型的空数据结构.但是,我似乎无法编译它,好像我的函数通过签名返回接口但实际上返回一个实现,它抱怨.

这是我的意思的简化示例和操场样本:

https://play.golang.org/p/LxY55BC59D

package main

import "fmt"


type DataPoint interface {
    Create() 
}

type MetaData struct {
    UniqueId string
    AccountId int
    UserId int
}

type Conversion struct {
    Meta MetaData
    Value int
}

func (c *Conversion) Create() {
    fmt.Println("CREATE Conversion")
}

type Impression struct {
    Meta MetaData
    Count int
}

func (i *Impression) Create() {
    fmt.Println("CREATE Impression")
} 

func getDataPoint(t string) DataPoint {
    if t == "Conversion" {
        return &Conversion{}
    } else {
        return &Impression{}
    }
}



func main() {
    meta := MetaData{
        UniqueId: "ID123445X",
        AccountId: 1,
        UserId: 2,
    }
    dpc := getDataPoint("Conversion")
    dpc.Meta = meta
    dpc.Value = 100
    dpc.Create()

    fmt.Println(dpc)

    dpi :=  getDataPoint("Impression")
    dpi.Meta = meta
    dpi.Count = 42
    dpi.Create()

    fmt.Println(dpi)

}
Run Code Online (Sandbox Code Playgroud)

汇编产生:

prog.go:51: dpc.Meta undefined (type DataPoint has no field or method Meta)
prog.go:52: dpc.Value undefined (type DataPoint has no field or method Value)
prog.go:58: dpi.Meta undefined (type DataPoint has no field or method Meta)
prog.go:59: dpi.Count undefined (type DataPoint has no field or method Count)
Run Code Online (Sandbox Code Playgroud)

Ain*_*r-G 7

没有类型断言,您无法访问类似的字段.您只能在接口上调用方法,它对其实现细节一无所知.如果确实需要访问这些字段,请使用类型断言:

dpc := getDataPoint("Conversion")
dpc.(*Conversion).Meta = meta
dpc.(*Conversion).Value = 100
dpc.Create()

dpi := getDataPoint("Impression")
dpi.(*Impression).Meta = meta
dpi.(*Impression).Count = 42
dpi.Create()
Run Code Online (Sandbox Code Playgroud)

游乐场:https://play.golang.org/p/Ije8hfNcWS.