安装过程略过,网上搜一大把。

介绍

本文会在一个module中开发一个简单的Go package。

同时介绍go tool(也就是go命令行)。

以及如何fetch,build和install Go的modules,packages,commands。

代码组织

Go是按packages来组织代码的。一个package == 一个目录。

同一个package中的functions,types,variables,和constants是共享的。也就是包访问权限,java默认也是包访问权限。

packages是放在module中的,module是通过go.mod文件来定义的。典型的,一个repository只有一个go.mod,放在根目录。

可以使用go mod init name来创建这个文件。在go run后会生成go.sum文件,内容是go.mod的加密哈希。

repository也允许有多个module,module的packages是go.mod所在的目录,如果子目录也有go.mod,那么这个子目录的packages就属于子目录module。

第一个程序

假设module path是example.com/user/hello

$ mkdir hello # Alternatively, clone it if it already exists in version control.
$ cd hello
$ go mod init example.com/user/hello
go: creating new go.mod: module example.com/user/hello
$ cat go.mod
module example.com/user/hello go 1.14
$

Go源文件的第一个语句必须是package name。程序入口必须是package main

package main

import "fmt"

func main() {
fmt.Println("Hello, world.")
}

喜闻乐见Hello World。

现在可以build和install,

$ go install example.com/user/hello
$

这条命令会build然后生成可执行二进制文件(这是我比较喜欢Go的一个原因,直接生成可执行文件,省去了安装依赖的麻烦)。

buildinstall命令都可以生成可执行文件。不同点在于

  • go build 不能生成包文件, go install 可以生成包文件
  • go build 生成可执行文件在当前目录下, go install 生成可执行文件在bin目录下

install生成文件的bin目录是根据环境变量来的。按以下顺序检查

  • GOBIN
  • GOPATH

如果都没有设置,就会生成到默认GOPATH(Linux $HOME/go 或Windows %USERPROFILE%\go)。

示例的二进制文件会生成到$HOME/go/bin/hello(Windows的话就是%USERPROFILE%\go\bin\hello.exe)。

可以查看环境变量GOBIN和GOPATH的值

go env

也可以设置GOBIN

$ go env -w GOBIN=/somewhere/else/bin
$

设置后可以重置

$ go env -u GOBIN
$

GOPATH需要到系统环境变量进行修改。

install等命令需要在源文件目录下执行,准确点说是“当前工作目录”。否则会报错。

在当前目录执行,以下等价

$ go install example.com/user/hello
$ go install .
$ go install

验证下结果,为了方便,添加install目录到PATH

# Windows users should consult https://github.com/golang/go/wiki/SettingGOPATH
# for setting %PATH%.
$ export PATH=$PATH:$(dirname $(go list -f '{{.Target}}' .))
$ hello
Hello, world.
$

如果cd到了install的bin目录,也可以直接

$ hello
Hello, world.
$

现阶段Go的很多库都是放在GitHub等代码托管网站上面的,使用Git进行提交

$ git init
Initialized empty Git repository in /home/user/hello/.git/
$ git add go.mod hello.go
$ git commit -m "initial commit"
[master (root-commit) 0b4507d] initial commit
1 file changed, 7 insertion(+)
create mode 100644 go.mod hello.go
$

Go命令通过请求相应的HTTPS URL,并读取嵌入在HTML响应中的元数据<meta>标签,来定位包含给定module path的repository

Bitbucket (Git, Mercurial)

	import "bitbucket.org/user/project"
import "bitbucket.org/user/project/sub/directory" GitHub (Git) import "github.com/user/project"
import "github.com/user/project/sub/directory" Launchpad (Bazaar) import "launchpad.net/project"
import "launchpad.net/project/series"
import "launchpad.net/project/series/sub/directory" import "launchpad.net/~user/project/branch"
import "launchpad.net/~user/project/branch/sub/directory" IBM DevOps Services (Git) import "hub.jazz.net/git/user/project"
import "hub.jazz.net/git/user/project/sub/directory"

很多托管网站已经为Go的repository提供了元数据,为了共享module,最简单的办法就是让module path匹配repository的URL。

从module import packages

先在名字为morestrings的package中创建一个reverse.go文件,实现字符串反转

// Package morestrings implements additional functions to manipulate UTF-8
// encoded strings, beyond what is provided in the standard "strings" package.
package morestrings // ReverseRunes returns its argument string reversed rune-wise left to right.
func ReverseRunes(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}

由于ReverseRunes函数是大写的,所以是公有的,可以被其他packages import。

先build测试下编译成功

$ cd $HOME/hello/morestrings
$ go build
$

因为只是在package中,不是在module根目录,go build不会生成文件,而是会把compile后的package保存到local build cache中。

接着在hello.go中import

package main

import (
"fmt" "example.com/user/hello/morestrings"
) func main() {
fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))
}

然后install hello

$ go install example.com/user/hello

验证,import成功,字符串反转

$ hello
Hello, Go!

从远程remore modules import packages

可以用import path通过版本控制系统来获取package源码,如Git或Mercurial。

示例,使用github.com/google/go-cmp/cmp

package main

import (
"fmt" "example.com/user/hello/morestrings"
"github.com/google/go-cmp/cmp"
) func main() {
fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))
fmt.Println(cmp.Diff("Hello World", "Hello Go"))
}

当运行命令go install go build go run的时候,go命令会自动下载远程module,然后写到go.mod文件中

$ go install example.com/user/hello
go: finding module for package github.com/google/go-cmp/cmp
go: downloading github.com/google/go-cmp v0.4.0
go: found github.com/google/go-cmp/cmp in github.com/google/go-cmp v0.4.0
$ hello
Hello, Go!
string(
- "Hello World",
+ "Hello Go",
)
$ cat go.mod
module example.com/user/hello go 1.14 require github.com/google/go-cmp v0.4.0
$

国内容易超时,可以使用代理走国内镜像

七牛云

go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct

阿里云

go env -w GO111MODULE=on
go env -w GOPROXY=https://mirrors.aliyun.com/goproxy/,direct

module依赖会自动下载到GOPATH指定目录的pkg/mod子目录。

module指定版本的下载内容,是在所有其他require这个版本的modules中共享的,所以go命令会标记这些文件和目录为只读的。

可以使用命令删除所有下载的modules

$ go clean -modcache
$

测试

Go有个轻量的测试框架,go testtesting package

测试框架识别以_test.go结尾的文件,包含TestXXX命名的函数,函数签名func (t *testing.T)。如果函数调用失败如t.Errort.Fail,那么test就会失败。

示例,新建$HOME/hello/morestrings/reverse_test.go文件,添加morestrings package的测试代码

package morestrings

import "testing"

func TestReverseRunes(t *testing.T) {
cases := []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
}
for _, c := range cases {
got := ReverseRunes(c.in)
if got != c.want {
t.Errorf("ReverseRunes(%q) == %q, want %q", c.in, got, c.want)
}
}
}

运行测试

$ go test
PASS
ok example.com/user/morestrings 0.165s
$

版权申明:本文为博主原创文章,转载请保留原文链接及作者。

Go测试开发(一) 怎么写Go代码的更多相关文章

  1. NX二次开发-NX+VS写代码设断点调试技巧

    在做NX二次开发的时候写完代码,编译可以通过,但是执行的时候却没有反应,或者得到的结果不对,说明肯定有地方传值出错了.我在查找代码错误的时候有几种方法:1.uc1601打印函数输入和输出的值看对不对. ...

  2. 技术调研,IDEA 插件怎么开发「脚手架、低代码可视化编排、接口生成测试」?

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 不踩些坑,根本不是成熟的码农! 你觉得肯德基全家桶是什么?一家人一起吃的桶吗,就那么 ...

  3. ESP8266开发之旅 进阶篇⑤ 代码规范 —— 像写文章一样优美

    1.前言     之前,一直在跟大伙分享怎么去玩蓝牙模块,怎么去玩wifi模块,怎么去玩json,然后有很多小伙伴就留言各种问题或者说直接怼他的代码过来让我看,然后我就一脸懵逼(代码中到处各种abcd ...

  4. 为企业应用开发提速,写给企业IT部门的低代码开发基础知识

    简介:应用程序开发长期以来一直是IT部门和业务部门面临的问题. IT部门总是被新的应用程序需求弄得不堪重负.他们不可能完成业务部门想要完成的每一个项目. 同时,业务部门的用户厌倦了等待,并开始完全绕过 ...

  5. 笔试测试开发题三道(python)

    笔试遇到的三道测试开发题,虽然都不难,但关键还是思路吧!我想在开发东西的时候应该具备的就是思路,有了思路尝试去写,或查相关文档或代码,在此基础上需要不断调整最终达到需求.思路又是在不断练习中获得的. ...

  6. Android NDK开发(五)--C代码回调Java代码【转】

    转载请注明出处:http://blog.csdn.net/allen315410/article/details/41862479 在上篇博客里了解了Java层是怎样传递数据到C层代码,并且熟悉了大部 ...

  7. 什么是测试开发工程师-google的解释

    什么是测试开发工程师-google的解释 “ 软件测试开发工程师[SET or Software Engineer in Test],和软件开发工程师一样是开发工程师,主要负责软件的可测试性.他们参与 ...

  8. 翻译一篇文章:It's Difficult to Grow a Test Developer(成为测试开发工程师的艰辛)

    翻译一篇文章:It's Difficult to Grow a Test Developer(成为测试开发工程师的艰辛)   以下文章是送给来poptest学习测试开发工程师的学员们,很多人想测试工程 ...

  9. 测试开发Python培训:抓取新浪微博抓取数据-技术篇

    测试开发Python培训:抓取新浪微博抓取数据-技术篇   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.在poptest的se ...

随机推荐

  1. SCOI2020迷惑记

    睡了个好觉还是很困但没咋吃饭就出门了. 到了之后随便跟认得到的人扯了两句就进去了. 结果让我们站在外面等... 然后通知说不能自带水和吃的那我这个中午没吃饭的咋整啊. 马上啃了半块巧克力就进了考场,然 ...

  2. Kubeflow实战: 入门介绍与部署实践

    更多内容关注专辑: 机器学习实战 1 介绍 Kubeflow是在k8s平台之上针对机器学习的开发.训练.优化.部署.管理的工具集合,内部集成的方式融合机器学习中的很多领域的开源项目,比如Jupyter ...

  3. 关于import android.support.v4.app.ContextCompat;找不到contextcompat的解决方法

    android迁移到了androidx,那么相关库的import就有问题了,需要转变为androidx的,这里比如 import android.support.v4.app.ContextCompa ...

  4. Java—io流之打印流、 commons-IO

    打印流 打印流根据流的分类: 字节打印流  PrintStream 字符打印流  PrintWriter /* * 需求:把指定的数据,写入到printFile.txt文件中 * * 分析: * 1, ...

  5. java循环语句while与do-while

    一 while循环 while循环语句和选择结构if语句有些相似,都是根据条件判断来决定是否执行大括号内的执行语句. 区别在于,while语句会反复地进行条件判断,只要条件成立,{}内的执行语句就会执 ...

  6. 45道Promise面试题

    来看看通过阅读本篇文章要点: Promise的几道基础题 Promise结合setTimeout Promise中的then.catch.finally Promise中的all和race async ...

  7. Spring Boot系列(三):Spring Boot整合Mybatis源码解析

    一.Mybatis回顾 1.MyBatis介绍 Mybatis是一个半ORM框架,它使用简单的 XML 或注解用于配置和原始映射,将接口和Java的POJOs(普通的Java 对象)映射成数据库中的记 ...

  8. 使用 codeblocks 编写C++ udp组播程序遇到的问题

    编译错误 会出现好多undefined reference to'WSAStartup to@8之类的错误,都是undefind开头的 解决方法: Settings -> Compiler se ...

  9. Cannot instantiate the type ......的解决

    使用public abstract class MainWindow implements ActionListener{} 之后创建对象MainWindow window = new MainWin ...

  10. xfs文件系统修复方法

    1. 前言首先尝试mount和umount文件系统,以便重放日志,修复文件系统,如果不行,再进行如下操作.fdisk -l 查看硬盘分区情况mount -l 查看文件系统挂载情况df -h 查看文件系 ...