Tutorial: Create a Go module - go.dev

文章推薦指數: 80 %
投票人數:10人

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>



請為這篇文章評分?