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
  • 相关阅读:
    tar命令解压jdk.tar.gz包 报错 gzip: stdin: not in gzip format
    CentOS6.5安装完没有网络的解决办法
    UML在需求分析阶段的应用
    UML
    UML在软件开发中各个阶段的作用和意义
    Maven那点事儿(Eclipse版)
    eclipse和myeclipse的下载地址
    div的作用
    c:if标签数据回显判断是否选中
    《Hadoop》对于高级编程Hadoop实现构建企业级安全解决方案
  • 原文地址:https://www.cnblogs.com/xiaqiuchu/p/14196882.html
Copyright © 2011-2022 走看看