You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言中如何传递接口实现以调用CallImplementation方法?

解决方法

你的repositories包中的FindSomethingInDatabase是普通函数,并没有实现ObjectAPI接口。Go语言中只有结构体方法才能实现接口,所以需要先调整代码结构,再完成调用。

1. 修改repositories包代码,实现ObjectAPI接口

首先定义一个结构体作为方法接收者,将原函数改为该结构体的方法,以此实现接口:

package repositories

// 定义结构体作为方法接收者
type ObjectRepo struct{}

// 将原函数改为ObjectRepo的方法,实现interfaces.ObjectAPI接口
func (r *ObjectRepo) FindSomethingInDatabase(ctx context.Context, name string) (e.Response, error) {
    statement, err := db.SqlStatementWithCtx(ctx,
        `SELECT * 
         FROM table
         WHERE name = ? LIMIT 1`)
    if err != nil { // 修正原代码的错误判断顺序,先检查语句创建是否失败
        return e.Response{}, err
    }
    defer statement.Close() // 用defer确保资源自动释放,避免泄漏

    row := statement.QueryRowContext(ctx, name)
    return toResponse(row), nil
}

2. 调用CallImplementation的正确方式

在业务逻辑中创建ObjectRepo的实例,直接传入CallImplementation即可:

// 示例:在业务逻辑包中调用
import (
    "your-project-path/dto"
    "your-project-path/interfaces"
    "your-project-path/repositories"
)

func HandleRequest(request *dto.XRequest) dto.XResponse {
    // 创建接口实现的实例
    repo := &repositories.ObjectRepo{}
    // 传入实例调用目标方法
    return CallImplementation(request, repo)
}

3. 编写Mock实现用于测试

如果需要Mock数据库操作,只需定义另一个实现ObjectAPI接口的Mock结构体:

// 示例:测试用的Mock实现
type MockObjectRepo struct{}

func (m *MockObjectRepo) FindSomethingInDatabase(ctx context.Context, name string) (e.Response, error) {
    // 返回模拟的响应数据或错误,用于测试场景
    return e.Response{ID: 1, Name: name}, nil
}

测试时传入Mock实例:

func TestCallImplementation(t *testing.T) {
    mockRepo := &MockObjectRepo{}
    testRequest := &dto.XRequest{Ctx: context.Background(), Name: "test"}
    response := CallImplementation(testRequest, mockRepo)
    // 这里添加断言逻辑,验证响应是否符合预期
}

内容的提问来源于stack exchange,提问作者daocc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:20:38