How to Write Go Code - go.dev
文章推薦指數: 80 %
Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables ...
WhyGo
GetStarted
Docs
Packages
Play
Blog
HowtoWriteGoCode
Introduction
ThisdocumentdemonstratesthedevelopmentofasimpleGopackageinsidea
moduleandintroducesthegotool,thestandardwayto
fetch,build,andinstallGomodules,packages,andcommands.
Note:ThisdocumentassumesthatyouareusingGo1.13orlaterandthe
GO111MODULEenvironmentvariableisnotset.Ifyouarelookingfor
theolder,pre-modulesversionofthisdocument,itisarchived
here.
Codeorganization
Goprogramsareorganizedintopackages.Apackageisacollection
ofsourcefilesinthesamedirectorythatarecompiledtogether.Functions,
types,variables,andconstantsdefinedinonesourcefilearevisibletoall
othersourcefileswithinthesamepackage.
Arepositorycontainsoneormoremodules.Amoduleisacollection
ofrelatedGopackagesthatarereleasedtogether.AGorepositorytypically
containsonlyonemodule,locatedattherootoftherepository.Afilenamed
go.modtheredeclaresthemodulepath:theimportpath
prefixforallpackageswithinthemodule.Themodulecontainsthepackagesin
thedirectorycontainingitsgo.modfileaswellassubdirectories
ofthatdirectory,uptothenextsubdirectorycontaininganother
go.modfile(ifany).
Notethatyoudon'tneedtopublishyourcodetoaremoterepositorybeforeyou
canbuildit.Amodulecanbedefinedlocallywithoutbelongingtoarepository.
However,it'sagoodhabittoorganizeyourcodeasifyouwillpublishit
someday.
Eachmodule'spathnotonlyservesasanimportpathprefixforitspackages,
butalsoindicateswherethegocommandshouldlooktodownloadit.
Forexample,inordertodownloadthemodulegolang.org/x/tools,
thegocommandwouldconsulttherepositoryindicatedby
https://golang.org/x/tools(describedmorehere).
Animportpathisastringusedtoimportapackage.Apackage's
importpathisitsmodulepathjoinedwithitssubdirectorywithinthemodule.
Forexample,themodulegithub.com/google/go-cmpcontainsapackage
inthedirectorycmp/.Thatpackage'simportpathis
github.com/google/go-cmp/cmp.Packagesinthestandardlibrarydo
nothaveamodulepathprefix.
Yourfirstprogram
Tocompileandrunasimpleprogram,firstchooseamodulepath(we'lluse
example/user/hello)andcreateago.modfilethat
declaresit:
$mkdirhello#Alternatively,cloneitifitalreadyexistsinversioncontrol.
$cdhello
$gomodinitexample/user/hello
go:creatingnewgo.mod:moduleexample/user/hello
$catgo.mod
moduleexample/user/hello
go1.16
$
ThefirststatementinaGosourcefilemustbe
packagename.Executablecommandsmustalwaysuse
packagemain.
Next,createafilenamedhello.goinsidethatdirectorycontaining
thefollowingGocode:
packagemain
import"fmt"
funcmain(){
fmt.Println("Hello,world.")
}
Nowyoucanbuildandinstallthatprogramwiththegotool:
$goinstallexample/user/hello
$
Thiscommandbuildsthehellocommand,producinganexecutable
binary.Ittheninstallsthatbinaryas$HOME/go/bin/hello(or,
underWindows,%USERPROFILE%\go\bin\hello.exe).
TheinstalldirectoryiscontrolledbytheGOPATH
andGOBINenvironment
variables.IfGOBINisset,binariesareinstalledtothat
directory.IfGOPATHisset,binariesareinstalledto
thebinsubdirectoryofthefirstdirectoryin
theGOPATHlist.Otherwise,binariesareinstalledto
thebinsubdirectoryofthedefaultGOPATH
($HOME/goor%USERPROFILE%\go).
Youcanusethegoenvcommandtoportablysetthedefaultvalue
foranenvironmentvariableforfuturegocommands:
$goenv-wGOBIN=/somewhere/else/bin
$
Tounsetavariablepreviouslysetbygoenv-w,usegoenv-u:
$goenv-uGOBIN
$
Commandslikegoinstallapplywithinthecontextofthemodule
containingthecurrentworkingdirectory.Iftheworkingdirectoryisnotwithin
theexample/user/hellomodule,goinstallmayfail.
Forconvenience,gocommandsacceptpathsrelative
totheworkingdirectory,anddefaulttothepackageinthe
currentworkingdirectoryifnootherpathisgiven.
Soinourworkingdirectory,thefollowingcommandsareallequivalent:
$goinstallexample/user/hello
$goinstall.
$goinstall
Next,let'sruntheprogramtoensureitworks.Foraddedconvenience,we'll
addtheinstalldirectorytoourPATHtomakerunningbinaries
easy:
#Windowsusersshouldconsulthttps://github.com/golang/go/wiki/SettingGOPATH
#forsetting%PATH%.
$exportPATH=$PATH:$(dirname$(golist-f'{{.Target}}'.))
$hello
Hello,world.
$
Ifyou'reusingasourcecontrolsystem,nowwouldbeagoodtimetoinitialize
arepository,addthefiles,andcommityourfirstchange.Again,thisstepis
optional:youdonotneedtousesourcecontroltowriteGocode.
$gitinit
InitializedemptyGitrepositoryin/home/user/hello/.git/
$gitaddgo.modhello.go
$gitcommit-m"initialcommit"
[master(root-commit)0b4507d]initialcommit
1filechanged,7insertion(+)
createmode100644go.modhello.go
$
ThegocommandlocatestherepositorycontainingagivenmodulepathbyrequestingacorrespondingHTTPSURLandreadingmetadataembeddedintheHTMLresponse(see
gohelpimportpath).
Manyhostingservicesalreadyprovidethatmetadataforrepositoriescontaining
Gocode,sotheeasiestwaytomakeyourmoduleavailableforotherstouseis
usuallytomakeitsmodulepathmatchtheURLfortherepository.
Importingpackagesfromyourmodule
Let'swriteamorestringspackageanduseitfromthehelloprogram.
First,createadirectoryforthepackagenamed
$HOME/hello/morestrings,andthenafilenamed
reverse.gointhatdirectorywiththefollowingcontents:
//PackagemorestringsimplementsadditionalfunctionstomanipulateUTF-8
//encodedstrings,beyondwhatisprovidedinthestandard"strings"package.
packagemorestrings
//ReverseRunesreturnsitsargumentstringreversedrune-wiselefttoright.
funcReverseRunes(sstring)string{
r:=[]rune(s)
fori,j:=0,len(r)-1;i
延伸文章資訊
- 1Create Your First Golang App - Hackers and Slackers
Golang's GOPATH is a directory where all your Go code and project dependencies live. ... To give ...
- 2Build a Simple To-Do List App in Golang - Better Programming
I wish I could participate and contribute to OSS Golang projects in the future. ... create a data...
- 3golang/example: Go example projects - GitHub
Clone the project. $ git clone https://go.googlesource.com/example $ cd example.
- 4albertwidi/go-project-example - GitHub
Go Project Example. Contribute to albertwidi/go-project-example development by creating an accoun...
- 57 GitHub projects to make you a better Go Developer - DEV ...
This repo contains a basic layout for Go application projects. ... This repo has a list of Go fun...