Go语言-第一个程序和Go tools (fmt, run, build, install)

本文介绍了Go语言的基础使用,包括go fmt进行代码格式化,go run用于本地快速运行,go build编译为本地可执行文件,以及go install用于构建和安装可发布的程序。详细讲解了各个命令的用法和注意事项,同时提供了实例来展示Go项目的工程结构和编译流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 初步使用

1.1 Go工具

常用的Go工具只有不多的几个命令:

  • go fmt
  • go run
  • go build
  • go install

Go语言有自己的严格的格式,一个好习惯是在提交代码前先用内置的格式调整程序调整一下格式:

go fmt
go fmt xxx.go
go fmt xxx

最简单的情况,就在.go文件所在目录下运行上述命令,那么当前目录下所有的.go文件就都处理了。
可以带参数指定目标文件或者目标包,只要GOPATH设定的没问题,能够找到包,这个命令就可以成功运行,统一格式我还是赞同的,起码阅读代码会有比较统一的体验。

本地试运行、调试,用:

go run xxx.go
go run *.go

注意:以上.go源文件必须包含带有main函数的那个.go源文件,只有其他的.go源文件是不能运行的。

编译成本地可执行文件:

go build xxx.go
go build xxx
go build

然后可执行文件可以直接运行。如果不指定文件,那么当前文件夹内含有main函数的.go源文件编译,然后生成一个跟目录名称一样的可执行文件。注意如果指定xxx.go,那么也是含有main函数的那个.go文件。

编译成成可发布的可执行文件:

go install xxx
go install

1.2 实例

在linux可以使用“make geth”,那在window下输入什么命令可以达到相应目的,以下是Makefile文件中的内容:“# This Makefile is meant to be used by people that do not usually work # with Go source code. If you know what GOPATH is then you probably # don't need to bother with make. .PHONY: geth all test lint fmt clean devtools help GOBIN = ./build/bin GO ?= latest GORUN = go run #? geth: Build geth. geth: $(GORUN) build/ci.go install ./cmd/geth @echo "Done building." @echo "Run \"$(GOBIN)/geth\" to launch geth." #? all: Build all packages and executables. all: $(GORUN) build/ci.go install #? test: Run the tests. test: all $(GORUN) build/ci.go test #? lint: Run certain pre-selected linters. lint: ## Run linters. $(GORUN) build/ci.go lint #? fmt: Ensure consistent code formatting. fmt: gofmt -s -w $(shell find . -name "*.go") #? clean: Clean go cache, built executables, and the auto generated folder. clean: go clean -cache rm -fr build/_workspace/pkg/ $(GOBIN)/* # The devtools target installs tools required for 'go generate'. # You need to put $GOBIN (or $GOPATH/bin) in your PATH to use 'go generate'. #? devtools: Install recommended developer tools. devtools: env GOBIN= go install golang.org/x/tools/cmd/stringer@latest env GOBIN= go install github.com/fjl/gencodec@latest env GOBIN= go install google.golang.org/protobuf/cmd/protoc-gen-go@latest env GOBIN= go install ./cmd/abigen @type "solc" 2> /dev/null || echo 'Please install solc' @type "protoc" 2> /dev/null || echo 'Please install protoc' #? help: Get more info on make commands. help: Makefile @echo '' @echo 'Usage:' @echo ' make [target]' @echo '' @echo 'Targets:' @sed -n 's/^#?//p' $< | column -t -s ':' | sort | sed -e 's/^/ /'”
03-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值