Go Design Patterns | Packt

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

Go is a multi-paradigm programming language that has built-in facilities to create concurrent applications. Design patterns allow developers to efficiently ... BrowseAll FreeLearning Signin Subscribe Aboutthisbook Goisamulti-paradigmprogramminglanguagethathasbuilt-infacilitiestocreateconcurrentapplications.Designpatternsallowdeveloperstoefficientlyaddresscommonproblemsfacedduringdevelopingapplications. GoDesignPatternswillprovidereaderswithareferencepointtosoftwaredesignpatternsandCSPconcurrencydesignpatternstohelpthembuildapplicationsinamoreidiomatic,robust,andconvenientwayinGo. ThebookstartswithabriefintroductiontoGoprogrammingessentialsandquicklymovesontoexplaintheideabehindthecreationofdesignpatternsandhowtheyappearedinthe90’sasacommon"language"betweendeveloperstosolvecommontasksinobject-orientedprogramminglanguages.Youwillthenlearnhowtoapplythe23GangofFour(GoF)designpatternsinGoandalsolearnaboutCSPconcurrencypatterns,the"killerfeature"inGothathashelpedGoogledevelopsoftwaretomaintainthousandsofservers. Withallofthisthebookwillenableyoutounderstandandapplydesignpatternsinanidiomaticwaythatwillproduceconcise,readable,andmaintainablesoftware. Publicationdate: February2017 Publisher Packt Pages 402 ISBN 9781786466204   DownloadcodefromGitHub RelatedTags: NewReleases Django AJAX WebDevelopment MostPopular   Chapter 1. Ready...Steady...Go!DesignPatternshavebeenthefoundationforhundredsofthousandsofpiecesofsoftware.SincetheGangOfFour(ErichGamma,RichardHelm,RalphJohnsonandJohnVlissides)wrotethebookDesignPatterns:ElementsofReusableObject-OrientedSoftwarein1994withexamplesinC++andSmalltalk,thetwenty-threeclassicpatternshavebeenre-implementedinmostofmajorlanguagesoftodayandtheyhavebeenusedinalmosteveryprojectyouknowabout.TheGangofFourdetectedthatmanysmallarchitectureswerepresentinmanyoftheirprojects,theystartedtorewritetheminamoreabstractwayandtheyreleasedthefamousbook.ThisbookisacomprehensiveexplanationandimplementationofthemostcommondesignpatternsfromtheGangofFourandtoday'spatternsplussomeofthemostidiomaticconcurrencypatternsinGo.ButwhatisGo...?   AlittlebitofhistoryOnthelast20years,wehavelivedanincrediblegrowthincomputerscience.Storagespaceshavebeenincreaseddramatically,RAMhassufferedasubstantialgrowth,andCPU'sare...well...simplyfaster.HavetheygrownasmuchasstorageandRAMmemory?Notreally,CPUindustryhasreachedalimitinthespeedthattheirCPU'scandeliver,mainlybecausetheyhavebecomesofastthattheycannotgetenoughpowertoworkwhiletheydissipateenoughheat.TheCPUmanufacturersarenowshippingmorecoresoneachcomputer.Thissituationcrashesagainstthebackgroundofmanysystemsprogramminglanguagesthatweren'tdesignedformulti-processorCPUsorlargedistributedsystemsthatactasauniquemachine.InGoogle,theyrealizedthatthiswasbecomingmorethananissuewhiletheywerestrugglingtodevelopdistributedapplicationsinlanguageslikeJavaorC++thatweren'tdesignedwithconcurrencyinmind.Atthesametime,ourprogramswerebigger,morecomplex,moredifficulttomaintainandwitha lotofroomforbadpractices.Whileourcomputershadmorecoresandwerefaster,wewerenotfasterwhendevelopingourcodeneitherourdistributedapplications.ThiswasGo'starget.Godesignstartedin2007bythreeGooglersintheresearchofaprogramminglanguagethatcouldsolvecommonissuesinlargescaledistributedsystemsliketheonesyoucanfindatGoogle.Thecreatorswere:RobPike:Plan9andInfernoOS.RobertGriesemer:WorkedatGoogle'sV8JavaScriptenginethatpowersGoogleChrome.KenThompson:WorkedatBelllabsandtheUnixteam.IthasbeeninvolvedindesigningofthePlan9operatingsystemaswellasthedefinitionoftheUTF-8encoding.In2008,thecompilerwasdoneandtheteamgotthehelpofRussCoxandIanLanceTaylor.Theteamstartedtheirjourneytoopensourcetheprojectin2009andinMarch2012theyreachedaversion1.0aftermorethanfiftyreleases.   InstallingGoAnyGoInstallationneedstwobasicthings:thebinariesofthelanguagesomewhereonyourdiskandaGOPATHpathinyoursystemwhereyourprojectsandtheprojectsthatyoudownloadfromotherpeoplewillbestored.Inthefollowinglines,wewillexplorehowtoinstallGobinariesinLinux,WindowsandOSX.ForadetailedexplanationofhowtoinstallthelatestversionofGo,youcanrefertotheofficialdocumentationathttps://golang.org/doc/install.LinuxToinstallGoinLinuxyouhavetwooptions: Easyoption:Useyourdistributionpackagemanager: RHEL/Fedora/CentosuserswithYUM/DNF: sudoyuminstall-ygolang Ubuntu/DebianusersusingAPTwith: sudoapt-getinstall-ygolang Advanced:Downloadingthelatestdistributionfrom https://golang.org. Irecommendusingthesecondanddownloadingadistribution.Go'supdatesmaintainsbackwardcompatibilityandyouusuallyshouldnotbeworriedaboutupdatingyourGobinariesfrequently.GoLinuxadvancedinstallationTheadvancedinstallationofGoinLinuxrequiresyoutodownloadthebinariesfromgolangwebpage.Afterentering https://golang.org ,clicktheDownloadGobutton(usuallyattheright)someFeaturedDownloadsoptionisavailableforeachdistribution.SelectLinuxdistributiontodownloadthelateststableversion.NoteAt https://golang.orgyoucanalsodownloadbetaversionsofthelanguage.Let'ssaywehavesavedthetar.gz fileinDownloadsfoldersolet'sextractitandmoveittoadifferentpath.Byconvention,Gobinariesareusuallyplacedin/usr/local/godirectory:tar-zxvfgo*.*.*.linux-amd64.tar.gz sudomvgo/usr/local/go Onextractionremembertoreplaceasterisks(*)withtheversionyouhavedownloaded.NowwehaveourGoinstallationin/usr/local/gopathsonowwehavetoaddthebinsubfoldertoourPATHandthebinfolderwithinourGOPATH.mkdir-p$HOME/go/bin With-pwearetellingbashtocreatealldirectoriesthatarenecessary.NowweneedtoappendbinfolderpathstoourPATH,appendthefollowinglinesattheendofyour~/.bashrc:exportPATH=$PATH:/usr/local/go/bin Checkthatourgo/bin directoryisavailable:$goversion Goversiongo1.6.2linux/amd64 WindowsToinstallGoinWindows,youwillneedadministratorprivileges.Openyourfavoritebrowserandnavigateto https://golang.org .OncethereclicktheDownloadGobuttonandselectMicrosoftWindowsdistribution.A*.msifilewillstartdownloading.ExecutetheMSIinstallerbydoubleclickingit.AninstallerwillappearaskingyoutoaccepttheEndUserLicenseAgreement(EULA)andselectatargetfolderforyourinstallation.WewillcontinuewiththedefaultpaththatinmycasewasC:\Go.OncetheinstallationisfinishedyouwillhavetoaddthebinaryGofolder,locatedinC:\Go\bintoyourPath.Forthis,youmustgotoControlPanelandselectSystemoption.OnceinSystem,selecttheAdvancedtabandclicktheEnvironmentvariablesbutton.Hereyou'llfindawindowwithvariablesforyourcurrentuserandsystemvariables.Insystemvariables,you'llfindthePathvariable.ClickitandclicktheEdit  buttontoopenatextbox.Youcanaddyourpathbyadding;C:\Go/binattheendofthecurrentline(notethesemicolonatthebeginningofthepath).InrecentWindowsversions(Windows10)youwillhaveamanagertoaddvariableseasily.MacOSXInMacOSXtheinstallationprocessisverysimilartoLinux.Openyourfavoritebrowserandnavigateto https://golang.org andclicktheDownloadGo.Fromthelistofpossibledistributionsthatappear,selectAppleOSX.Thiswilldownloada*.pkgfiletoyourdownloadfolder.AwindowwillguideyouthroughtheinstallationprocesswhereyouhavetotypeyouradministratorpasswordsothatitcanputGobinaryfilesin/usr/local/go/binfolderwiththeproperpermissions.Now,openTerminaltotesttheinstallationbytypingthisonit:$goversion Goversiongo1.6.2darwin/amd64 Ifyouseetheinstalledversion,everythingwasfine.Ifitdoesn'tworkcheckthatyouhavefollowedcorrectlyeverysteporrefertothedocumentationat https://golang.org.Settingtheworkspace-LinuxandAppleOSXGowillalwaysworkunderthesameworkspace.Thishelpsthecompilertofindpackagesandlibrariesthatyoucouldbeusing.ThisworkspaceiscommonlycalledGOPATH.GOPATHhasaveryimportantroleinyourworkingenvironmentwhiledevelopingGosoftware.Whenyouimportalibraryinyourcodeitwillsearchforthislibraryinyour$GOPATH/src.ThesamewhenyouinstallsomeGoapps,binarieswillbestoredin$GOPATH/bin.Atthesame,allyoursourcecodemustbestoredinavalidroutewithin$GOPATH/srcfolder.Forexample,IstoremyprojectsinGitHubandmyusernameisSaydenso,foraprojectcalledminimal-mesos-go-frameworkIwillhavethisfolderstructurelike $GOPATH/src/github.com/sayden/minimal-mesos-go-frameworkwhichreflectstheURIwherethisrepoisstoredatGitHub:mkdir-p$HOME/go The$HOME/gopathisgoingtobethedestinationofour$GOPATH.Wehavetosetanenvironmentvariablewithour$GOPATHpointingtothisfolder.Tosettheenvironmentvariable,openagainthefile$HOME/.bashrcwithyourfavoritetexteditorandaddthefollowinglineattheendofit:exportGOPATH=${HOME}/go Savethefileandopenanewterminal.Tocheckthateverythingisworking,justwriteanechotothe$GOPATHvariablelikethis:echo$GOPATH /home/mcastro/go IftheoutputoftheprecedingcommandpointstoyourchosenGopath,everythingiscorrectandyoucancontinuetowriteyourfirstprogram.   StartingwithHelloWorldThiswouldn'tbeagoodbookwithoutaHelloWorldexample.OurHelloWorldexamplecan'tbesimpler,openyourfavoritetexteditorandcreateafilecalledmain.gowithinour$GOPATH/src/[your_name]/hello_worldwiththefollowingcontent:packagemain funcmain(){ println("HelloWorld!") } Savethefile.Torunourprogram,opentheTerminalwindowofyouroperatingsystem:InLinux,gotoprogramsandfindaprogramcalledTerminal.InWindows,hitWindows+R,typecmdwithoutquotesonthenewwindowandhitEnter.InMacOSX,hitCommand+Spacetoopenaspotlightsearch,typeterminalwithoutquotes.TheterminalappmustbehighlightedsohitEnter.Onceweareinourterminal,navigatetothefolderwherewehavecreatedourmain.gofile.Thisshouldbeunderyour$GOPATH/src/[your_name]/hello_worldandexecuteit:gorunmain.go HelloWorld! That'sall.Thegorun[file]commandwillcompileandexecuteourapplicationbutitwon'tgenerateanexecutablefile.Ifyouwantjusttobuilditandgetanexecutablefile,youmustbuildtheappusingthe followingcommand:gobuild-ohello_world Nothinghappens.Butifyousearchinthecurrentdirectory(lscommandinLinuxandMacOSX;anddirinWindows),you'llfindanexecutablefilewiththenamehello_world.Wehavegiventhisnametotheexecutablefilewhenwewrote-ohello_worldcommandwhilebuilding.Youcannowexecutethisfile:/hello_world HelloWorld! Andourmessageappeared!InWindows,youjustneedtotypethenameofthe.exefiletogetthesameresult.TipThegorun[my_main_file.go]commandwillbuildandexecutetheappwithoutintermediatefiles. Thegobuild-o[filename]commandwillcreateanexecutablefilethatIcantakeanywhereandhasnodependencies.   IntegratedDevelopmentEnvironment-IDEAnIDE(IntegratedDevelopmentEnvironment)isbasicallyauserinterfacetohelpdevelopers,codetheirprogramsbyprovidingasetoftoolstospeedupcommontasksduringdevelopmentprocesslikecompiling,building,ormanagingdependencies.TheIDEsarepowerfultoolsthattakesometimetomasterandthepurposeofthisbookisnottoexplainthem(anIDElikeEclipsehasitsownbooks).InGo,youhavemanyoptionsbutthereareonlytwothatarefullyorientedtoGodevelopment LiteIDEandIntellijGogland.LiteIDEisnotthemostpowerfulthoughbutIntellijhasputlotsofeffortstomakeGoglandaveryniceeditorwithcompletion,debugging,refactoring,testing,visualcoverage,inspections,etc.CommonIDEsortexteditorsthathaveaGoplugin/integrationareasfollowing:IntelliJIdeaSublimeText2/3AtomEclipseButyoucanalsofindGopluginsfor:VimVisualStudioandVisualCodeTheIntelliJIdeaandAtomIDEs,forthetimeofthiswriting,hasthesupportfordebuggingusingaplugincalledDelve.TheIntelliJIdeaisbundledwiththeofficialGoplugin.InAtomyou'llhavetodownloadaplugincalledGo-plusandadebuggerthatyoucanfindsearchingthewordDelve.   TypesTypesgivetheusertheabilitytostorevaluesinmnemonicnames.Allprogramminglanguageshavetypesrelatedwithnumbers(tostoreintegers,negativenumbers,orfloatingpointforexample)withcharacters(tostoreasinglecharacter)withstrings(tostorecompletewords)and soon.Golanguagehasthecommontypesfoundinmostprogramminglanguages:TheboolkeywordisforBooleantypewhichrepresentsaTrueorFalsestate.Manynumerictypesbeingthemostcommon: Theinttyperepresentsanumberfrom0to4294967295in32bitsmachinesandfrom0to18446744073709551615in64bits.Thebytetyperepresentsanumberfrom0to255.Thefloat32andfloat64typesarethesetofallIEEE-75464/-bitfloating-pointnumbersrespectively.Youalsohavesignedinttypelikerunewhichisanaliasofint32type,anumberthatgoesfrom-2147483648to2147483647andcomplex64andcomplex128whicharethesetofallcomplexnumberswithfloat32/float64realandimaginarypartslike2.0i. Thestringkeywordforstringtyperepresentsanarrayofcharactersenclosedinquoteslike"golang"or"computer".Anarraythatisanumberedsequenceofelementsofasingletypeandafixedsize(moreaboutarrayslaterinthischapter).Alistofnumbersorlistsofwordswithafixedsizeisconsideredarrays.Theslicetypeisasegmentofanunderlyingarray(moreaboutthislaterinthischapter).Thistypeisabitconfusingatthebeginningbecauseitseemslikeanarraybutwewillseethatactually,theyaremorepowerful.Thestructuresthataretheobjectsthatarecomposedofanotherobjectsortypes.Thepointers(moreaboutthislaterinthischapter)arelikedirectionsinthememoryofourprogram(yes,likemailboxesthatyoudon'tknowwhat'sinside).Thefunctionsareinteresting(moreaboutthislaterinthischapter).Youcanalsodefinefunctionsasvariablesandpassthemtootherfunctions(yes,afunctionthatusesafunction,didyoulikeInceptionmovie?).Theinterfaceisincrediblyimportantforthelanguageastheyprovidemanyencapsulationandabstractionfunctionalitiesthatwe'llneedoften.We'lluseinterfacesextensivelyduringthebookandtheyarepresentedingreaterdetaillater.Themaptypesareunorderedkey-valuestructures.Soforagivenkey,youhaveanassociatedvalue.ThechannelsarethecommunicationprimitiveinGoforconcurrencyprograms.We'lllookonchannelswithmoredetailonChapter8,DealingwithGo'sCSPconcurrency.   VariablesandconstantsVariablesarespacesincomputer'smemorytostorevaluesthatcanbemodifiedduringtheexecutionoftheprogram.Variablesandconstantshaveatypeliketheonesdescribedinprecedingtext.Although,youdon'tneedtoexplicitlywritethetypeofthem(althoughyoucandoit).ThispropertytoavoidexplicittypedeclarationiswhatiscalledInferredtypes.Forexample://Explicitlydeclaringa"string"variable varexplicitstring="Hello,I'maexplicitlydeclaredvariable" Herewearedeclaringavariable(withthekeywordvar)calledexplicitofstringtype.Atthesametime,wearedefiningthevaluetoHelloWorld!.//Implicitlydeclaringa"string".Typeinferred inferred:=",I'maninferredvariable" Butherewearedoingexactlythesamething.Wehaveavoidedthevarkeywordandthestringtypedeclaration.Internally,Go'scompilerwillinfer(guess)thetypeofthevariabletoastringtype.Thiswayyouhavetowritemuchlesscodeforeachvariabledefinition.Thefollowinglinesusethereflectpackagetogatherinformationaboutavariable.Weareusingittoprintthetypeof(the TypeOf variableinthecode)ofbothvariables:fmt.Println("Variable'explicit'isoftype:", reflect.TypeOf(explicit)) fmt.Println("Variable'inferred'isoftype:", reflect.TypeOf(inferred)) Whenweruntheprogram,theresultisthefollowing:$gorunmain.go Hello,I'maexplicitlydeclaredvariable Hello,I'maninferredvariable Variable'explicit'isoftype:string Variable'inferred'isoftype:string Asweexpected,thecompilerhasinferredthetypeoftheimplicitvariabletostringtoo.Bothhavewrittentheexpectedoutputtotheconsole.   OperatorsTheoperatorsareusedtoperformarithmeticoperationsandmakecomparisonsbetweenmanythings.ThefollowingoperatorsarereservedbyGolanguage. Mostcommonlyusedoperatorsarethearithmeticoperatorsandcomparators.Arithmeticoperatorsareasfollowing:The+operatorforsumsThe-operatorforsubtractionsThe*operatorformultiplicationsThe/operatorfordivisionsThe%operatorfordivisionremaindersThe++operatortoadd1tothecurrentvariableThe--operatortosubtract1tothecurrentvariableOntheotherside,comparatorsareusedtocheckthedifferencesbetweentwostatements:The==operatortocheckiftwovaluesareequalThe!=operatortocheckiftwovaluesaredifferentThe>operatortocheckifleftvalueishigherthanrightvalueThe=operatortocheckifleftvalueishigherorequaltorightvalueThe<=operatortocheckifleftvalueislowerorequaltorightvalueThe&&operatortocheckiftwovaluesaretrue Youalsohavetheshifterstoperforma binaryshifttoleftorrightofavalueandanegatedoperatortoinvertsomevalue.We´llusetheseoperatorsalotduringthefollowingchapterssodon´tworrytoomuchaboutthemnow,justkeepinmindthatyoucannotsetthenameofanyvariable,fieldorfunctioninyourcodelikethisoperators.TipWhat'stheinvertedvalueof10?What'sthenegatedvalueof10?-10?Incorrect..10inbinarycodeis1010soifwenegateevery numberwewillhave0101or101whichisthenumber5.   FlowcontrolFlowcontrolisreferredastheabilitytodecidewhichportionofcodeorhowmanytimesyouexecutesomecodeonacondition.InGo,itisimplementedusingfamiliarimperativeclauseslikeif,else,switchandfor.Thesyntaxiseasytograsp.Let´sreviewmajorflowcontrolstatementsinGo.Theif...elsestatementGolanguage,likemostprogramminglanguages,hasif…elseconditionalstatementforflowcontrol.The Syntaxissimilartootherlanguagesbutyoudon'tneedtoencapsulatetheconditionbetweenparenthesis:ten:=10 iften==20{ println("Thisshouldn'tbeprintedas10isn'tequalto20") }else{ println("Tenisnotequalsto20"); } Theelse...ifconditionworksinasimilarfashion,youdon'tneedparentheseseitherandtheyaredeclaredasprogrammerwouldexpect:if"a"=="b"||10==10||true==false{ println("10isequalto10") }elseif11==11&&"go"=="go"{ println("Thisisn'tprintbecausepreviousconditionwassatisfied"); }else{ println("Incasenoconditionissatisfied,printthis") } } NoteGodoesnothaveternaryconditionslikecondition?true:false.TheswitchstatementTheswitchstatementisalsosimilartomostimperativelanguages.Youtakeavariableandcheckpossiblevaluesforit:number:=3 switch(number){ case1: println("Numberis1") case2: println("Numberis2") case3: println("Numberis3") } Thefor…rangestatementThe_for_loopisalsosimilarthanincommonprogramminglanguagesbutyoudon'tuseparentheseseitherfori:=0;i<=10;i++{ println(i) } Asyouhaveprobablyimaginedifyouhavecomputersciencebackground,weinferanintvariabledefinedas0andexecutethecodebetweenthebracketswhilethecondition(i<=10)issatisfied.Finally,foreachexecution,weadded1tothevalueofi.Thiscodewillprintthenumbersfrom0to10.Youalsohaveaspecialsyntaxtoiterateoverarraysorsliceswhichisrange:forindex,value:=rangemy_array{ fmt.Printf("Indexis%dandvalueis%d",index,value) } First,thefmt(format)isaverycommonGopackagethatwewilluseextensivelytogiveshapetothemessagethatwewillprintintheconsole.Regardingfor,youcanusetherangekeywordtoretrieveeveryiteminacollectionlikemy_arrayandassignthemtothevaluetemporalvariable.Itwillalsogiveyouanindexvariabletoknowthepositionofthevalueyou'reretrieving.It'sequivalenttowritethefollowing:forindex:=0,index Whathappenedintheresult?Thisiswhywedescribedtheobjectasdangerous.Youcanpointtoanillocationwhenusingthismodeifyoucallanon-existingkeyintheJSON.Notonlythis,likeintheexample,itcouldalsointerpretavalueasafloat64whenitissimplyabyte,wastinga lotofmemory.Soremembertojustusemap[string]interface{}whenyouneeddirtyquickaccesstoJSONdatathatisfairlysimpleandyouhaveundercontrolthetypeofscenariosdescribedpreviously.   GotoolsGocomeswithaseriesofusefultoolstoeasethedevelopmentprocesseveryday.Alsointhegolangpageof GitHub,therearesometoolsthataresupportedbytheGoteambuttheyarenotpartofthecompiler.Mostoftheprojectsusetoolssuchas gofmtsothatallthecodebaselookssimilar.GodochelpsustofindusefulinformationinGo'sdocumentationandthe goimportcommandtoauto-importthepackagesweareusing.Let'sseethem.ThegolinttoolAlinteranalyzessourcecodetodetecterrorsorimprovements.The golintlinterisavailableon https://github.com/golang/lint forinstallation(itdoesn'tcomebundledwiththecompiler).ItisveryeasytouseandisintegratedsomeIDEstoberunwhenyousaveasourcecodefile(AtomorSublimeText,forexample).Doyouremembertheimplicit/explicitcodethatwerunwhentalkingaboutvariables?Let'slintit://Explicitlydeclaringa"string"variable varexplicitstring="Hello,I'maexplicitlydeclaredvariable" //Implicitlydeclaringa"string". Typeinferredinferred:=",I'maninferredvariable" $golintmain.go Themain.go:10:21: commandshouldomitthetypestringfromthe declarationofthe explicitString variable;itwillbeinferredfromtheright-handside.ItistellingusthatGocompilerwillactuallyinferthistypeofa variablefromthecodeandyoudon'tneedtodeclareitstype.Whataboutthe Train typeontheinterfacesection?TypeTrainstruct{ TrainWidthint } $golintmain.go Themain.go:5:6:typeexportedTraintypeshouldhavea commentorremainnotexported.Inthiscase,it'spointingusthatapublictypesuchas Train typemustbecommentedsothatuserscanreadthegenerateddocumentationtoknowitsbehavior.ThegofmttoolThegofmttoolcomesbundledwiththecompilerthatalreadyhasaccesstoit.Itspurposeistoprovideasetofindentation,formatting,spacingandfewotherrulestoachievegood-lookingGocode.Forexample,let'stakethecodeofHelloWorldandmakeitabitweirderbyinsertingspaceseverywhere:packagemain funcmain(){ println("HelloWorld!") } $gofmtmain.go packagemain funcmain(){ println("HelloWorld!") } Thegofmtcommandprintsitcorrectlyagain.Whatismore,wecanusethe-wflagtooverwritetheoriginalfile:$gofmt-wmain.go Andnowwe'llhaveourfileproperlycorrected.ThegodoctoolGodocumentationisprettyextendedandverbose.Youcanfinddetailedinformationaboutanytopicyouwanttoachieve.Thegodoctoolalsohelpsyouaccessthisdocumentationdirectlyfromthecommandline.Forexample,wecanquerythepackageencoding/json:$godoccmd/encoding/json [...] FUNCTIONS funcCompact(dst*bytes.Buffer,src[]byte)error CompactappendstodsttheJSON-encodedsrcwithinsignificantspace characterselided. funcHTMLEscape(dst*bytes.Buffer,src[]byte) [...] Youcanalsousegrep,abashutilityforLinuxandMac,tofindspecificinformationaboutsomefunctionality.Forexample,we'llusegreptolookfortextthatmentionsanythingaboutparsingJSONfiles:$godoccmd/encoding/json|grepparse TheUnmarshalcommandparsestheJSONencodeddataandstorestheresultintheobjectbeingparsed.Oneofthethingsthatthe golintcommandwarnsaboutistousethebeginningofacommentwiththesamenameofthefunctionitdescribes.Thisway,ifyoudon'trememberthenameofthefunctionthatparsesJSON,youcanusegodocwithgrepandsearchforparsesothebeginningofthelinewillalwaysbethefunctionnamelikeintheexampleprecedingtheUnmarshalcommand.ThegoimporttoolThegoimporttoolisamusthaveinGo.Sometimesyourememberyourpackagessowellthatyoudon'tneedtosearchmuchtoremembertheirAPIbutit'smoredifficulttoremembertheprojecttheybelongtowhendoingtheimport.Thegoimportcommandhelpsyoubysearchingyour$GOPATHforoccurrencesofapackagethatyoucouldbeusingtoprovideyouwiththeprojectimportlineautomatically.ThisisveryusefulifyouconfigureyourIDEtorungoimportonsavesothatallusedpackagesinthesourcefileareimportedautomaticallyifyouusedthem.Italsoworkstheotherwayaround--ifyoudeletethefunctionyouwereusingfromapackageandthepackageisn'tbeingusedanymore,itwillremovetheimportline.   ContributingtoGoopensourceprojectsinGitHubOneimportantthingtomentionaboutGopackagingsystemisthatitneedstohaveaproperfolderstructurewithintheGOPATH.ThisintroducesasmallproblemwhenworkingwithGitHubprojects.Weareusedtoforkingaproject,cloningourforkandstartworkingbeforecommittingthepull-requesttotheoriginalproject.Wrong!Whenyouforkaproject,youcreateanewrepositoryonGitHubwithinyourusername.Ifyouclonethisrepositoryandstartworkingwithit,allnewimportreferencesintheprojectwillpointtoyourrepositoryinsteadoftheoriginal!Imaginethefollowingcaseintheoriginalrepository:packagemain import"github.com/original/a_library" [somecode] Then,youmakeaforkandaddasubfolderwithalibrarycalleda_library/my_librarythatyouwanttousefromthemainpackage.Theresultisgoingtobethefollowing:packagemain import( "github.com/original/a_library" "github.com/myaccount/a_library/my_library" ) Nowifyoucommitthisline,theoriginalrepositorythatcontainsthecodeyouhavepushedwilldownloadthiscodeanywaysfromyouraccountagainanditwillusethereferencesdownloaded!Nottheonescontainedintheproject!So,thesolutiontothisissimplytoreplacethegitclone commandwithagogetpointingtotheoriginallibrary:$gogetgithub.com/original/a_library $cd$GOPATH/src/github.com/original/a_library $gitremoteaddmy_originhttps://github.com/myaccount/a_libbrary Withthismodification,youcanworknormallyintheoriginalcodewithoutfearasthereferenceswillstaycorrect.Onceyouaredoneyoujusthavetocommitandpushtoyourremote.$gitpushmy_originmy_brach Thisway,youcannowaccesstheGitHubwebuserinterfaceandopenthepullrequestwithoutpollutingtheactualoriginalcodewithreferencestoyouraccount.   SummaryAfterthisfirstchapter,youmustbefamiliarwiththesyntaxofGoandsomeofthecommand-linetoolsthatcomebundledwiththecompiler.Wehaveleftapartconcurrencycapabilitiesforalaterchapterastheyarelargeandprettycomplextograspatthebeginningsothatthereaderlearnsthesyntaxofthelanguagefirst,becomesfamiliarandconfidentwithit,andthentheycanjumptounderstanding CommunicatingSequentialProcesses(CSP)concurrencypatternsanddistributedapplications.Thenextstepsaretostartwiththecreationaldesignpatterns. Readmore Unlockthisbookforjust$5amonthforthefirst5months AbouttheAuthor MarioCastroContreras MarioCastroContrerasisasoftwareengineerwhohasspecializedindistributedsystemsandbigdatasolutions.Heworksasasitereliabilityengineer,andnowheisfocusedoncontainerizedsolutionsandappsusingmostofGoogleCloudsuite,especiallyKubernetes.Hehasbroadexperienceinsystemsandsolutionsintegration,andhehaswrittenmanyscalableandreliable12-factorappsusingGoandDocker.HehasdesignedBigDataarchitecturesforfinancialservicesandmedia,andhehaswrittendataprocessingpipelinesusingevent-drivenarchitectureswrittenpurelyinGo. Heisalsoveryactiveintheopensourcecommunity,andyoucanfindhimonhisGitHubaccountwiththeusernamesayden.Inthepast,hehasalsowrittenmobileapplicationsandbackendsinJava.Marioispassionateaboutprogramminglanguages,andhefoundthebestbalancebetweenfunandproductivityinGo;however,recentlyhehasenjoyedwritinginRustandembeddedsystemsinC.Heisalsopassionateaboutroadcyclingandwintersports. Browsepublicationsbythisauthor IneededhelpunderstandinghowtoapplycommondesignpatternstoGolang.ThebookdefinitelydeliversinthisrespectandI'mgratefultotheauthorforcreatingthecontent. Withthatsaid,Icouldn'tvoteithigherduetothemistakesfoundinsomeoftheexamplesthatcosttheuserintermsoftime.Ifyou'renewtothelanguage,thecodeexamplesmaythrowyouoff.Throughoutthebook,youwillfindthatthetextdiffersfromthecodeblocks(examples)whichalsodifferfromthecodesamplesthatareavailablefordownload.Evenwhenattemptingtorunsomeofthecodeexamplescreatedbytheauthor,theysimplydidn'twork. Iwillsay,iftheauthorweretorevisethebook,itwouldbeaperfectresource. 3 07October2018 TrustedCustomer Iguessthisisagoodplaceforeditorialcomments. Pg23:samplecodeshouldread"result:=addFive(6)" and"//5+6mustprint11" Pg30:Theappartmentbuilding/housemetaphorforpointersisreallyrough. Howabout...Ineedameasurementofalivingroom. Callbyvalue,wouldduplicatetheentirehouse,putitonatruckandbringittomesoIcanmeasurethelivingroom. ItwouldbemoreefficientifIjustwenttothehouse'addressandmeasuredtheoriginallivingroom. Pg31:after"number:=5" add"pointer_to_number:=&number" Pg35:'TDD'usedwithoutexpansion.TDDisnotdefineduntilpg38. IreallyliketheTestDrivenDesignapproach. Pg:40:Iwouldrewordthefirstlinetoinserttheword'executable'beforebinaryfile. Pg44:IntheMyObjectstruct,itshouldbe`json:"string"` not`json:"number"` 4 12May2018 nospam3 Verygoodbook,butdoesn'tlookgoodonkindle 5 31December2017 KhabibMurtuzaaliev Hands-OnSoftwareEngineeringwithGolang Exploresoftwareengineeringmethodologies,techniques,andbestpracticesinGoprogrammingtobuildeasy-to-maintainsoftwarethatcaneffortlesslyscaleondemand ByAchilleasAnagnostopoulos Jan2020 640pages Unlockthisbookandthefulllibraryfor$5amonth* Expires: Getallthequalitycontentyou’lleverneedtostayaheadwithaPacktsubscription–accessover7,500onlinebooksandvideosoneverythingintech.*$5amonthforthefirst5months. Startnow ×



請為這篇文章評分?