gpt4 book ai didi

去导入本地包

转载 作者:行者123 更新时间:2023-12-01 22:07:10 24 4
gpt4 key购买 nike

我有一个 main.go

package main

import (
"context"
"fmt"
"log"

model "model"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)

func handler(...){
}

我尝试导入目录 model 中的模型该文件名为 model.go
它只包含:
package model

type xxx struct {
xxx
}

我尝试主要导入它,但出现错误:
build: cannot load model: cannot find module providing package model

最佳答案

如果您的模块 model不是本地的,那么您可以使用 Tonys 答案,它会正常工作,但如果您在本地使用此模块,则需要在 go.mod 中添加路径文件。

例如,本地模块 model仅包含 model.go其中有以下内容

package model

type Example struct {
Name string
}

func (e *Example) Foo() string {
return e.Name
}

对于这个本地模块,必须必须使用命令 go mod init model 来初始化模块。以及 ./model/go.mod 的内容将会
module model
go 1.13

在要导入此模块的主模块中,您需要添加以下行
require model v1.0.0
replace model v1.0.0 => {Absolute or relative path to the model module}

所以,你的 main测试模块的 go.mod文件看起来像这样
module main

require model v1.0.0
replace model v1.0.0 => ./model

go 1.13

通过设置,您可以在 test 中使用此模块只有 import "model" 的模块

因此,当使用 main 方法测试模块时
package main

import (
model "model"
)

func main() {
example := model.Example{
Name: "Hello World",
}
println(example.Foo())
}

输出将是
Hello World

关于去导入本地包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60919877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com