Go 语言学习系列(二) : 创建 module

  • 学习创建 module

基于上一篇的文件夹, 咱们新创建一个文件夹, 名字: greeting

然后执行命令:

go mod init example.com/greetings

image

创建好了, 看一下文件路径:

image

多了一个文件: go.mod

这个文件是记录咱们 code 的引用.

下面创建一个文件: 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
}

看到 go 的 fun 怎么写了吗:

image

声明一个本地变量:

var message string

好了, 到这就相当于创建一个 module 完事了, 其实就是一个类, 类里面一个方法. 下一步是怎么调用.

创建一个文件夹 hello, 然后执行命令:

go mod init example.com/hello

创建一个文件 hello.go, 把下面的 code 粘进去:

package main

import (
    "fmt"

    "example.com/greetings"
)

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

分析一下上面的 code:

  • 首先如果你想执行 go 程序, 程序必须有一个 main 入口.
  • 其他的没啥可分析的.

你现在马上执行是不好使的. 因为:

For production use, you’d publish the example.com/greetings module from its repository (with a module path that reflected its published location), where Go tools could find it to download it. For now, because you haven't published the module yet, you need to adapt the example.com/hello module so it can find the example.com/greetings code on your local file system.

使用 go mod edit command 改变引用到本地路径:

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

执行以后你看到的 go.mod 文件应该是这个样子的:

module example.com/hello

go 1.17

replace example.com/greetings => ../greetings

现在可以运行了吗? 正常来说可以, 但是按照规矩, 一般运行之前需要看一下是否有新的引用, 所以执行命令:

go mod tidy

image

现在 go.mod 变成这个样子了:

module example.com/hello

go 1.17

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000

此时就可以运行程序了:

image

到此我们学会了 module 发布和使用, 下一篇学习 error handle.

posted @ 2022-09-18 21:31  YanyuWu  阅读(97)  评论(0编辑  收藏  举报