创建模块
创建目录:mkdir greetings
进入目录:cd greetings
创建mod依赖:go mod init example/greetings
创建文件:greetings.go
编辑文件:#模块名与文件名,目录名均相同
package greetings
import "fmt"
func Hello(name string) string {
message := fmt.Sprintf("Hi, %v. Welcome!", name)
return message
}
创建主程序
返回greetings目录上层,创建目录:
cd ..
mkdir hello
cd hello
创建mod依赖:go mod init example/hello
创建文件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)
}
改变模块查找方式:改为相对地址
go mod edit -replace example.com/greetings=../greetings
更新依赖:go mod tidy
运行代码:go run .
返回错误
修改greetings.go
package greetings
import (
"errors"
"fmt"
)
func Hello(name string)(string, error){
if name == "" {
return "", errors.New("empty name")
}
message := fmt.Sprintf("Hi, %v. Welcome!", name)
return message, nil
}
修改hello.go
package main
import ( "fmt""log""example.com/greetings")
func main() {
log.SetPrefix("greetings: ")
log.SetFlags(0)
message, err := greetings.Hello("")
if err != nil {
log.Fatal(err)
}
fmt.Println(message)
}
网友评论