首页 > 解决方案 > 如何在 GOLANG 中导入本地包?

问题描述

我是 GO(和程序编程)的新手,我正在编写示例代码

我的 main.go 导入语句是

package main

 import (
     "fmt"
     "packagetest/mymath"
 )

 func main() {
     fmt.Println(mymath.Add(2, 3))
 }

我的 mymath.go 包是

package mymath

func Add(a, b int) int {
    return a + b
}

func sub(a, b int) int {
    return a - b
}  

我的 GOPATH 是 C:\Users\tonyf\Desktop\go-workspace-2.0

这是我的 main.go 所在的位置C:\Users\tonyf\Desktop\go-workspace-2.0\src\packagetest

这就是我的 mymath.go 所在的位置C:\Users\tonyf\Desktop\go-workspace-2.0\src\packagetest\mymath

当我运行 main.go 时,出现这样的错误 main.go:5:2: package packagetest/mymath is not in GOROOT (C:\Program Files\Go\src\packagetest\mymath)

和问题

could not import packagetest/mymath (cannot find package "packagetest/mymath" in any of 
    C:\Program Files\Go\src\packagetest\mymath (from $GOROOT)
    C\src\packagetest\mymath (from $GOPATH)
    \Users\tonyf\Desktop\go-workspace-2.0\src\packagetest\mymath (from $GOPATH))

请帮忙

标签: go

解决方案


你只需要先运行这个命令:

go mod init <appname>

在同一应用程序路径中。


推荐阅读