首页 > 解决方案 > 在两个文件中使用相同的类型声明时在 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,一切都没有错误地构建。

我不确定为什么会这样。我不能在不同的文件中使用相同的类型吗?

标签: gopointers

解决方案


不要定义Response两次(一次 inmain.go和一次 in utils/responses.go),而是utils.Response在您的main.go代码中使用:

func Handler(ctx context.Context) (utils.Response, error) {
...
}

推荐阅读