Tutorial: Create a Go module - go.dev
文章推薦指數: 80 %
Start by creating a Go module. In a module, you collect one or more related packages for a discrete and useful set of functions. For example, you might create a ... WhyGo GetStarted Docs Packages Play Blog Tutorial:CreateaGomodule Thisisthefirstpartofatutorialthatintroducesafewfundamental featuresoftheGolanguage.Ifyou'rejustgettingstartedwithGo,besure totakealookat Tutorial:GetstartedwithGo,whichintroduces thegocommand,Gomodules,andverysimpleGocode. Inthistutorialyou'llcreatetwomodules.Thefirstisalibrarywhichis intendedtobeimportedbyotherlibrariesorapplications.Thesecondisa callerapplicationwhichwillusethefirst. Thistutorial'ssequenceincludessevenbrieftopicsthateachillustratea differentpartofthelanguage. Createamodule--Writeasmallmodulewithfunctionsyoucancallfrom anothermodule. Callyourcodefromanothermodule-- Importanduseyournewmodule. Returnandhandleanerror--Addsimple errorhandling. Returnarandomgreeting--Handledata inslices(Go'sdynamically-sizedarrays). Returngreetingsformultiplepeople --Storekey/valuepairsinamap. Addatest--UseGo'sbuilt-inunittesting featurestotestyourcode. Compileandinstalltheapplication-- Compileandinstallyourcodelocally. Note:Forothertutorials,see Tutorials. Prerequisites Someprogrammingexperience.Thecodehereispretty simple,butithelpstoknowsomethingaboutfunctions,loops,andarrays. Atooltoedityourcode.Anytexteditoryouhavewill workfine.MosttexteditorshavegoodsupportforGo.Themostpopularare VSCode(free),GoLand(paid),andVim(free). Acommandterminal.Goworkswellusinganyterminalon LinuxandMac,andonPowerShellorcmdinWindows. Startamodulethatotherscanuse StartbycreatingaGomodule.Ina module,youcollectoneormorerelatedpackagesforadiscreteandusefulset offunctions.Forexample,youmightcreateamodulewithpackagesthathave functionsfordoingfinancialanalysissothatotherswritingfinancial applicationscanuseyourwork.Formoreaboutdevelopingmodules,see Developingandpublishingmodules. Gocodeisgroupedintopackages,andpackagesaregroupedintomodules.Your modulespecifiesdependenciesneededtorunyourcode,includingtheGo versionandthesetofothermodulesitrequires. Asyouaddorimprovefunctionalityinyourmodule,youpublishnewversions ofthemodule.Developerswritingcodethatcallsfunctionsinyourmodulecan importthemodule'supdatedpackagesandtestwiththenewversionbefore puttingitintoproductionuse. Openacommandpromptandcdtoyourhomedirectory. OnLinuxorMac: cd OnWindows: cd%HOMEPATH% CreateagreetingsdirectoryforyourGomodulesourcecode. Forexample,fromyourhomedirectoryusethefollowingcommands: mkdirgreetings cdgreetings Startyourmoduleusingthe gomodinitcommand. Runthegomodinitcommand,givingityourmodulepath-- here,useexample.com/greetings.Ifyoupublishamodule, thismustbeapathfromwhichyourmodulecanbedownloadedby Gotools.Thatwouldbeyourcode'srepository. Formoreonnamingyourmodulewithamodulepath,see Managing dependencies. $gomodinitexample.com/greetings go:creatingnewgo.mod:moduleexample.com/greetings Thegomodinitcommandcreatesago.modfiletotrackyour code'sdependencies.Sofar,thefileincludesonlythenameofyour moduleandtheGoversionyourcodesupports.Butasyouadddependencies, thego.modfilewilllisttheversionsyourcodedependson.Thiskeeps buildsreproducibleandgivesyoudirectcontroloverwhichmodule versionstouse. Inyourtexteditor,createafileinwhichtowriteyourcodeandcallit greetings.go. Pastethefollowingcodeintoyourgreetings.gofileandsavethefile. packagegreetings import"fmt" //Helloreturnsagreetingforthenamedperson. funcHello(namestring)string{ //Returnagreetingthatembedsthenameinamessage. message:=fmt.Sprintf("Hi,%v.Welcome!",name) returnmessage } Thisisthefirstcodeforyourmodule.Itreturnsagreetingtoany callerthatasksforone.You'llwritecodethatcallsthisfunctionin thenextstep. Inthiscode,you: Declareagreetingspackagetocollectrelatedfunctions. ImplementaHellofunctiontoreturnthegreeting. Thisfunctiontakesanameparameterwhosetypeis string.Thefunctionalsoreturnsastring. InGo,afunctionwhosenamestartswithacapitallettercanbe calledbyafunctionnotinthesamepackage.ThisisknowninGoas anexportedname.Formoreaboutexportednames,see Exportednamesinthe Gotour. Declareamessagevariabletoholdyourgreeting. InGo,the:=operatorisashortcutfordeclaringand initializingavariableinoneline(Gousesthevalueontherightto determinethevariable'stype).Takingthelongway,youmighthave writtenthisas: varmessagestring message=fmt.Sprintf("Hi,%v.Welcome!",name) Usethefmtpackage's Sprintffunctiontocreateagreetingmessage.The firstargumentisaformatstring,andSprintfsubstitutes thenameparameter'svalueforthe%vformat verb.Insertingthevalueofthenameparametercompletes thegreetingtext. Returntheformattedgreetingtexttothecaller. Inthenextstep,you'llcallthisfunctionfromanothermodule. Callyourcodefromanothermodule>
延伸文章資訊
- 1Go Module與Go get 常用參數說明 - 關於網路那些事...
不支持module,會從GOPATH 或vendor 來尋找。如果不是在GOPATH 執行go mod init 則會報錯。 GO111MODULE=auto, 會檢查當前目錄是否啟用go.mo...
- 2go modules 終於不會再被GOPATH綁死了 - iT 邦幫忙
可以使用GOProxy來解決某些地區無法使用go get的問題. 以往需要將vendor目錄一起提交到git, 避免CI/CD去拉到外部的依賴包. go modules有build cache,...
- 3Tutorial: Create a Go module - go.dev
Start by creating a Go module. In a module, you collect one or more related packages for a discre...
- 4深入Go Module之go.mod文件解析 - 鸟窝
Go module就是一组统一打版和发布的package的集合,在根文件下有go.mod文件定义module path和依赖库的版本,package以子文件夹的形式存在module中,对 ...
- 5[Day05] golang package & golang module - iT 邦幫忙
本文同步發表於: Sponge Records. 本文將會介紹什麼是golang package、golang module 在開發的時候,很難所有功能都自己刻,而且也要避免掉重複造輪的問題,因...