栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang 引入本地包报错 imported and not used: “xxxx“go

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang 引入本地包报错 imported and not used: “xxxx“go

golang 版本go1.16.13
在1.11以后用go mod 管理包
需要 set GO111MODULE=on
在引入本地包调用其他包中函数的时候一直报错imported and not used: "xxxx"go,以为是引入的包邮问题呢,实际上是掉用函数的时候没有写包名导致的。

下图中cal函数中没有写包名导致的。


记录下如何调用其他包下的函数:
在main.go中调用utils.go中的C函数。
目录结构如下
funcdemo–>main–>main.go
funcdemo–>utils–>utils.go

utils.go代码如下,包中创建了Cal函数

package utils

import "fmt"

//函数名首字母大写说明是public,大家都可以调用,首字母小写是私有的
func Cal(n1 float64, n2 float64, operator byte) float64 {
	var res float64
	switch operator {
	case '+':
		res = n1 + n2
	case '-':
		res = n1 - n2
	case '*':
		res = n1 * n2
	case '/':
		res = n1 / n2
	default:
		fmt.Println("输入有误")

	}
	return res
}

main.go代码如下,调用了utils包中Cal函数

package main

import (
	"fmt"
	"funcdemo/utils"
)

func main() {
	var n1 float64 = 1.2
	var n2 float64 = 2.3
	var operator byte = '+'
	result := utils.Cal(n1, n2, operator)
	fmt.Println("res=", result)
}

然后执行go mod init

C:goprojectsrcgo_codechapter06funcdemo>go mod init funcdemo
go: creating new go.mod: module funcdemo
go: to add module requirements and sums:
        go mod tidy

C:goprojectsrcgo_codechapter06funcdemo>dir
 驱动器 C 中的卷是 Windows
 卷的序列号是 94A9-B808

 C:goprojectsrcgo_codechapter06funcdemo 的目录

2022/01/26  16:50              .
2022/01/26  11:56              ..
2022/01/26  16:50                25 go.mod
2022/01/26  11:36              main
2022/01/26  00:36              utils
               1 个文件             25 字节

执行go run
C:goprojectsrcgo_codechapter06funcdemo>cd main
C:goprojectsrcgo_codechapter06funcdemomain>go run main.go
res= 3.5

常用的参数
set GO111MODULE=on

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908976.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号