调用自定义的包
- 创建被调用的包
mkdir test cd test go mod init example.com/test
cat test/test.go package test import "fmt" // func 定义函数 // Hello 函数名 // (name string) 可以接受一个字符串变量 // string 函数返回值是一个字符串类型 func Hello(name string) string { //等同python message=print("hi, %s.welcome"%name) message :=fmt.Sprintf("hi, %v. welcome!", name) return message }
- 创建调用的包
# 在test同一级别执行 mkdir hello cd hello go mod init example.com/hello
cat hello.go //main 是go语言的执行入口 package main import ( "fmt" "example.com/test" ) func main() { // 调用了example.com/test 中的 test.Hello函数 message := test.Hello("wangendao") fmt.Println(message) }
- 修改hello 下的go.mod 文件,在hello目录执行
# 把 example.com/test 包指向本地的 ../test目录 go mod edit -replace example.com/test=../test
- 同步代码依赖项,在hello目录执行
go mod tidy
- 执行
go run .
参考:
阅读以下 Go 知名的免费教程:
第一本 《The Little Go Book》https://learnku.com/docs/the-little-go-book
短小精湛,涵盖 Go 的语言基础,一两个小时内即可阅读完毕,社区有 中文译本 。
第二本《The Way to Go》https://learnku.com/docs/the-way-to-go
备受好评的教程,深入浅出,基本上涵盖 Go 语言的方方面面。中文命名 《Go 入门指南》,前往阅读 ,与社区 Wiki 一样,不要求学会,但是适合在你学习的不同阶段重复学习的课程。
第三本《Go Web 编程》https://learnku.com/docs/build-web-application-with-golang
使用 Go 做 Web 编程相关的课程。前往阅读。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏