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:\goproject\src\go_code\chapter06\funcdemo>go mod init funcdemo
go: creating new go.mod: module funcdemo
go: to add module requirements and sums:
        go mod tidy

C:\goproject\src\go_code\chapter06\funcdemo>dir
 驱动器 C 中的卷是 Windows
 卷的序列号是 94A9-B808

 C:\goproject\src\go_code\chapter06\funcdemo 的目录

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

执行go run
C:\goproject\src\go_code\chapter06\funcdemo>cd main
C:\goproject\src\go_code\chapter06\funcdemo\main>go run main.go
res= 3.5

常用的参数
set GO111MODULE=on

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值