golang實現自己的模塊並調用


官方教程地址:https://golang.google.cn/doc/tutorial/call-module-code

1.在代碼目錄創建一個目錄greetings 用來存放 greetings 模塊

2.生成go.mod文件 

// 官方文檔寫的是example.com/greetings,我這邊按照文件夾名字設置的 greetings
// 下面只運行一個
// 官方
go mod init example.com/greetings  
// 本文章 
go mod init greetings  

3.創建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
}

4.當前目錄在 greetings ,返回上一級並創建一個文件夾 hello。

5. 進入hello文件夾,創建 hello.go 並寫入

package main

import (
    "fmt"
    // 此處導入的名字和生成go.mod的命名相同,官網是"example.com/greetings",本文章改成了 “greetings”
    // 官網引入
   //  "example.com/greetings"
     // 本文章引入
    "greetings"
)

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

6.生成hello的go.mod

go mod init hello

7.設置引入模塊路徑,編輯 hello/go.mod

// 源文件應該是這樣
module hello
// go的版本和你安裝使用的版本相同
go 1.14

修改為

module hello

go 1.14

// 官方文檔
// replace example.com/greetings => ../greetings
// 本文章 
replace greetings => ../greetings

8.編譯

go build

9.查看 hello/go.mod 應該會變成

module hello

go 1.14

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

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

10. Linux or Mac 執行

./hello

Windows 執行

hello.exe

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM