go语言 包依赖管理-构建完整的依赖项目:目录结构及包的调用

目录结构:

<home>/
 |-- greetings/
 |-- hello/

1.分别进入对应目录创建以上目录结构
//bash切换到用户主目录
 cd $HOMEPAHT$ 
//bash新建greetings目录并进入该目录
mkdir greetings
cd greetings
//bash创建模组example.com/greetings
$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings
当前目录下新增greetings.go代码程序
package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}

//bash切换到用户主目录

 cd $HOMEPAHT$ 
//bash新建hello目录并进入该目录
mkdir hello
cd hello
//bash创建模组example.com/hello

$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello

2.当前目录下新增hello.go代码程序

package main

import (
    "fmt"
    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

3.bash引用包重定向

$ go mod edit -replace example.com/greetings=../greetings

4.bash检查当前模块的依赖关系,并移除不需要的依赖项。

$ go mod tidy

5.bash当前目录下执行go命令,系统自动会从当前目录内搜索main.go入口程序

$ go run .
Hi, Gladys. Welcome!
注:GitHub上面包的调用与此类似,不用第3部的重定向。将url地址前段的https://去掉即可(线上包的调用可能存在不可用的情况,要进行测试是否仍然可调用)
go语言的编码原则有很多要注意的地方,比如同一目录下共用一个包名,函数或方法可以互相调用。但是只有以大写字母开头的函数或方法,才能被外部包调用。一个项目有且仅有一个main.go
入口和package main包,通过入口调用同级或下级目录包及函数......编码规则后续根据学习情况,再做总结

参考来源:https://go.dev/doc
posted @ 2023-09-15 15:55  三生有幸格格  阅读(30)  评论(0编辑  收藏  举报