调用自定义的包

  1. 创建被调用的包
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
}
  1. 创建调用的包
# 在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)
}
  1. 修改hello 下的go.mod 文件,在hello目录执行
# 把 example.com/test 包指向本地的 ../test目录
go mod edit -replace example.com/test=../test
  1. 同步代码依赖项,在hello目录执行
go mod tidy
  1. 执行
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 编程相关的课程。前往阅读。

posted @ 2022-12-08 23:03  mingtian是吧  阅读(13)  评论(0编辑  收藏  举报