zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Debian apt-get 无法补全
    Python 字典排序
    Python 替换字符串
    Debian 7 64位安装 wine
    Python Virtualenv 虚拟环境
    ASP.NET MVC ModelState
    Oracle存储过程写法
    利用ODBC从SQLServer向Oracle中导数据
    web自定义控件UserControl
    工作笔记
  • 原文地址:https://www.cnblogs.com/xiaqiuchu/p/14196882.html
Copyright © 2011-2022 走看看