简体   繁体   English

Go 语言类型断言

[英]Go lang type assertion

I am trying to do dependency injection in golang with applying dependency inversion principle, so I have the following service我正在尝试通过应用依赖倒置原则在golang中进行依赖注入,所以我有以下服务

package account

import (
    types "zaClouds/modules/account/domain/types"
    "zaClouds/modules/shared"
)

type IPlanDomainService interface {
    GetUsagePlanById(string) *shared.Result[types.UsagePlan]
}

type PlanDomainService struct {
    usagePlanService types.IUsagePlanService
}

func (planDomainService *PlanDomainService) GetUsagePlanById(id string) *shared.Result[types.UsagePlan] {
    result := &shared.Result[types.UsagePlan]{}
    usagePlanResult := planDomainService.usagePlanService.GetPlanById(id)

    if usagePlanResult.Err != nil {
        result.Err = usagePlanResult.Err
        return result
    }
    result.Data = usagePlanResult.Data
    return result
}

func PlanDomainServiceFactory(usagePlanService types.IUsagePlanService) IPlanDomainService {
    return &PlanDomainService{usagePlanService: usagePlanService}
}

as you can see, it accepts another service with type IUsagePlanService如您所见,它接受另一个类型为IUsagePlanService的服务

and here is the interface for it这是它的界面

package account

import (
    "zaClouds/modules/shared"

    "github.com/shopspring/decimal"
)

type UsagePlan struct {
    ID          string
    Title       string
    Description interface{}
    PlanID      string
    Price       decimal.Decimal
    Duration    int
    Features    map[string]map[string]string
}
type IUsagePlanService interface {
    GetPlanById(string) *shared.Result[UsagePlan]
}

and here is the way I am injecting this service to domain service这是我将此服务注入域服务的方式

func DiInit(usagePlanService interface{}) domainServices.IPlanDomainService {
domainServices.PlanDomainServiceFactory(types.IUsagePlanService(usagePlanService))
    return domainServices.PlanDomainServiceFactory(usagePlanService.(types.IUsagePlanService))
}

as you can see, I am trying to do a type assertion but it doesn't work, and gives me the following error:如您所见,我正在尝试进行类型断言,但它不起作用,并给我以下错误:

panic: interface conversion: *usagePlan.UsagePlanRepository is not account.IUsagePlanService: missing method GetPlanById

Edit编辑

Here is the actual implementation for usagePlanService这是usagePlanService的实际实现

type IUsagePlanRepository interface {
    createClient(string) *http.Request
    GetPlanById(string) *shared.Result[usagePlanRepoModels.UsagePlan]
}

type UsagePlanRepository struct {
    plansEndpoint string
    httpClient    *http.Client
}

func (r *UsagePlanRepository) GetPlanById(id string) *shared.Result[usagePlanRepoModels.UsagePlan] {
    result := &shared.Result[usagePlanRepoModels.UsagePlan]{}

    req := r.createClient(id)
    resp, err := r.httpClient.Do(req)

    if err != nil {
        log.Println("failed to load plan details \n[ERROR]", err)
        result.Err = err
        return result
    }

    defer func() {
        bodyError := resp.Body.Close()

        if bodyError != nil {
            result.Err = bodyError
        }

    }()

    if result.Err != nil {
        return result
    }

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        utils.Logger.Error("failed to load plan details \n[ERROR]", err, nil)
        result.Err = err
        return result
    }

    if resp.StatusCode >= 400 {
        result.Err = errors.New(string(body))
        utils.Logger.Info("getPlanById", string(body))
    }

    getUsagePlanResponse, foundError := usagePlanRepoModels.CreateGetUsagePlanResponse(body)

    if foundError != nil {
        result.Err = foundError
        return result
    }

    result.Data = *getUsagePlanResponse
    return result

}

When using an interface, you need to define all functions that you will use with the same name and signature as the implementation.使用接口时,您需要使用与实现相同的名称和签名来定义您将使用的所有函数。

The error message you got indicates that the implementation and the interface are different.您收到的错误消息表明实现和接口不同。

The implementation is not shown in your question, but you defined the function for your interface like this: GetPlanById(string) *shared.Result[UsagePlan] .您的问题中未显示该实现,但您为您的界面定义了 function,如下所示: GetPlanById(string) *shared.Result[UsagePlan] Any deviation from it will result in error.任何偏离它都会导致错误。 One common mistake is with the pointers.一个常见的错误是指针。 Adding or removing the * to the return type will incur in error if it differs from the original.如果返回类型与原始类型不同,则在返回类型中添加或删除*将导致错误。

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

相关问题 如何在 Go[lang] 中将字节转换为字符串 - How To Convert Bytes Into Strings In Go[lang] 无服务器框架中 go lang“aws-go”的默认模板不起作用 - the default template for go lang "aws-go" in the serverless framwork isn't working 在 Go 中使用反射分配给类型定义 - Assigning to type definition using reflection in Go 扩展 Map 的类型是否仍然在 Go 中通过引用传递? - Is a type that extends a Map still passed by reference in Go? 如何在 Go 中创建泛型方法? (方法必须没有类型参数) - How to create generic method in Go? (method must have no type parameters) 在 Go-Lang 中,我如何获取 JSON 文件并引用 css - In Go-Lang how can i take JSON file and quote to css HTTP 发布 API 请求,使用 go 语言和 AWS 机密管理器 Z099FB995346F31C749F6E0E4 - HTTP Post API request using go lang with aws secrets manager header Firebase 无法将 java.lang.String 类型的 object 转换为类型 - Firebase Can't convert object of type java.lang.String to type 在 java.lang.String 类型的对象的 JSON 反序列化期间出现问题 - Issue during JSON deserialization of an object of type java.lang.String json:无法将数字解组为 Go 结构字段。字符串类型的数量 - json: cannot unmarshal number into Go struct field .Amount of type string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM