go - 在两个文件中使用相同的类型声明时在 Go 中出现错误
问题描述
我正在尝试在 Go 中编写一个 lambda 函数。我的main.go
:
package main
import (
"context"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/<username>/<project>/utils"
)
type Response events.APIGatewayProxyResponse
func Handler(ctx context.Context) (Response, error) {
return utils.StandardResponse("Successfully executed the create handler function", http.StatusOK), nil
}
func main() {
lambda.Start(Handler)
}
并且utils/responses.go
是:
package utils
import (
"github.com/aws/aws-lambda-go/events"
)
type Response events.APIGatewayProxyResponse
func StandardResponse(body string, statusCode int) Response {
return events.APIGatewayProxyResponse{
StatusCode: statusCode,
Body: string(body),
Headers: map[string]string{
"Access-Control-Allow-Origin": "*",
},
}
}
当我尝试构建项目时,出现以下错误:
# command-line-arguments
handlers/handler1/main.go:31:31: cannot use utils.StandardResponse("Successfully executed the create handler function", http.StatusOK) (type utils.Response) as type Response in return argument
但是,如果我停止使用Response events.APIGatewayProxyResponse 类型并改为替换Response
为,则此错误消失events.APIGatewayProxyResponse
,一切都没有错误地构建。
我不确定为什么会这样。我不能在不同的文件中使用相同的类型吗?
解决方案
不要定义Response
两次(一次 inmain.go
和一次 in utils/responses.go
),而是utils.Response
在您的main.go
代码中使用:
func Handler(ctx context.Context) (utils.Response, error) {
...
}
推荐阅读
- swift - 无法从 Firebase 检索 Int
- javascript - React:在浏览器背面/页面之间持久化状态或数据
- powerbi - 无法从 SQL Server 加载 PowerBi 中的历史数据
- angular - 根据条件对表单进行角度所需的验证
- ssms - 在 ssms SQLCMD 中运行 .txt 文件
- django - 更新 django 字段中的状态 - status CHOICES
- postgresql - 执行选择查询时出现共享内存不足错误
- python - 使用 lmfit 将信号拟合为方波形式
- docker - 如何在 Dockerfile 中预拉 docker 镜像?
- python - 如何将预先计算的距离矩阵(csv格式)导入python?