go创建module(Tutorial: Create a Go module)

Tutorial: Create a Go module

  • 说明
  • 目标
  • 1 创建module
    • 新建greeting文件夹
    • go mod init
  • 2 调用module
    • 可以用之前的hello.go
    • go.mod修改----replace的使用
  • 总结

说明

本文为go官方文档学习笔记
创建module
参考https://golang.org/doc/tutorial/create-module

目标

创建2个module

  • library
    被其他library和app导入
  • application
    使用第一个lib

1 创建module

新建greeting文件夹

go mod init

加路径
实际开发中,路径为url(自己写的module的下载url)
新建文件greeting.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的func名,首字母大写,可跨package调用
func Hello(name string) string
func 函数名(参数类型)返回类型
:= operator 声明并初始化一个变量

2 调用module

可以用之前的hello.go

package main

import "fmt"

//import "rsc.io/quote"
import "example.com/greeting"

func main() {
    //fmt.Println("Hello, World!")
    //fmt.Println(quote.Go())

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

go.mod修改----replace的使用

当前的greetings是未发布的module
实际开发中,应发布到server上,被调用时联网下载

  • 未发布的如何引用
    在go.mod中加入
replace example.com/greetings => ../greetings

go创建module(Tutorial: Create a Go module)_第1张图片

  • 使用go build编译
    生成hello可执行程序
    go.mod里自动加了依赖
  • 引用已发布的module
    go.mod忽略replace
    使用tag
require example.com/greetings v1.1.0

总结

module路径
go.mod里replace使用

你可能感兴趣的:(go)