go1.17_spec.html 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864
  1. <!--{
  2. "Title": "The Go Programming Language Specification",
  3. "Subtitle": "Version of Oct 15, 2021",
  4. "Path": "/ref/spec"
  5. }-->
  6. <h2 id="Introduction">Introduction</h2>
  7. <p>
  8. This is the reference manual for the Go programming language as it was for
  9. language version 1.17, in October 2021, before the introduction of generics.
  10. It is provided for historical interest.
  11. The current reference manual can be found <a href="/doc/go_spec.html">here</a>.
  12. For more information and other documents, see <a href="/">go.dev</a>.
  13. </p>
  14. <p>
  15. Go is a general-purpose language designed with systems programming
  16. in mind. It is strongly typed and garbage-collected and has explicit
  17. support for concurrent programming. Programs are constructed from
  18. <i>packages</i>, whose properties allow efficient management of
  19. dependencies.
  20. </p>
  21. <p>
  22. The grammar is compact and simple to parse, allowing for easy analysis
  23. by automatic tools such as integrated development environments.
  24. </p>
  25. <h2 id="Notation">Notation</h2>
  26. <p>
  27. The syntax is specified using Extended Backus-Naur Form (EBNF):
  28. </p>
  29. <pre class="grammar">
  30. Production = production_name "=" [ Expression ] "." .
  31. Expression = Alternative { "|" Alternative } .
  32. Alternative = Term { Term } .
  33. Term = production_name | token [ "…" token ] | Group | Option | Repetition .
  34. Group = "(" Expression ")" .
  35. Option = "[" Expression "]" .
  36. Repetition = "{" Expression "}" .
  37. </pre>
  38. <p>
  39. Productions are expressions constructed from terms and the following
  40. operators, in increasing precedence:
  41. </p>
  42. <pre class="grammar">
  43. | alternation
  44. () grouping
  45. [] option (0 or 1 times)
  46. {} repetition (0 to n times)
  47. </pre>
  48. <p>
  49. Lower-case production names are used to identify lexical tokens.
  50. Non-terminals are in CamelCase. Lexical tokens are enclosed in
  51. double quotes <code>""</code> or back quotes <code>``</code>.
  52. </p>
  53. <p>
  54. The form <code>a … b</code> represents the set of characters from
  55. <code>a</code> through <code>b</code> as alternatives. The horizontal
  56. ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various
  57. enumerations or code snippets that are not further specified. The character <code>…</code>
  58. (as opposed to the three characters <code>...</code>) is not a token of the Go
  59. language.
  60. </p>
  61. <h2 id="Source_code_representation">Source code representation</h2>
  62. <p>
  63. Source code is Unicode text encoded in
  64. <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
  65. canonicalized, so a single accented code point is distinct from the
  66. same character constructed from combining an accent and a letter;
  67. those are treated as two code points. For simplicity, this document
  68. will use the unqualified term <i>character</i> to refer to a Unicode code point
  69. in the source text.
  70. </p>
  71. <p>
  72. Each code point is distinct; for instance, upper and lower case letters
  73. are different characters.
  74. </p>
  75. <p>
  76. Implementation restriction: For compatibility with other tools, a
  77. compiler may disallow the NUL character (U+0000) in the source text.
  78. </p>
  79. <p>
  80. Implementation restriction: For compatibility with other tools, a
  81. compiler may ignore a UTF-8-encoded byte order mark
  82. (U+FEFF) if it is the first Unicode code point in the source text.
  83. A byte order mark may be disallowed anywhere else in the source.
  84. </p>
  85. <h3 id="Characters">Characters</h3>
  86. <p>
  87. The following terms are used to denote specific Unicode character classes:
  88. </p>
  89. <pre class="ebnf">
  90. newline = /* the Unicode code point U+000A */ .
  91. unicode_char = /* an arbitrary Unicode code point except newline */ .
  92. unicode_letter = /* a Unicode code point classified as "Letter" */ .
  93. unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ .
  94. </pre>
  95. <p>
  96. In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,
  97. Section 4.5 "General Category" defines a set of character categories.
  98. Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
  99. as Unicode letters, and those in the Number category Nd as Unicode digits.
  100. </p>
  101. <h3 id="Letters_and_digits">Letters and digits</h3>
  102. <p>
  103. The underscore character <code>_</code> (U+005F) is considered a letter.
  104. </p>
  105. <pre class="ebnf">
  106. letter = unicode_letter | "_" .
  107. decimal_digit = "0" … "9" .
  108. binary_digit = "0" | "1" .
  109. octal_digit = "0" … "7" .
  110. hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
  111. </pre>
  112. <h2 id="Lexical_elements">Lexical elements</h2>
  113. <h3 id="Comments">Comments</h3>
  114. <p>
  115. Comments serve as program documentation. There are two forms:
  116. </p>
  117. <ol>
  118. <li>
  119. <i>Line comments</i> start with the character sequence <code>//</code>
  120. and stop at the end of the line.
  121. </li>
  122. <li>
  123. <i>General comments</i> start with the character sequence <code>/*</code>
  124. and stop with the first subsequent character sequence <code>*/</code>.
  125. </li>
  126. </ol>
  127. <p>
  128. A comment cannot start inside a <a href="#Rune_literals">rune</a> or
  129. <a href="#String_literals">string literal</a>, or inside a comment.
  130. A general comment containing no newlines acts like a space.
  131. Any other comment acts like a newline.
  132. </p>
  133. <h3 id="Tokens">Tokens</h3>
  134. <p>
  135. Tokens form the vocabulary of the Go language.
  136. There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
  137. and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from
  138. spaces (U+0020), horizontal tabs (U+0009),
  139. carriage returns (U+000D), and newlines (U+000A),
  140. is ignored except as it separates tokens
  141. that would otherwise combine into a single token. Also, a newline or end of file
  142. may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
  143. While breaking the input into tokens,
  144. the next token is the longest sequence of characters that form a
  145. valid token.
  146. </p>
  147. <h3 id="Semicolons">Semicolons</h3>
  148. <p>
  149. The formal grammar uses semicolons <code>";"</code> as terminators in
  150. a number of productions. Go programs may omit most of these semicolons
  151. using the following two rules:
  152. </p>
  153. <ol>
  154. <li>
  155. When the input is broken into tokens, a semicolon is automatically inserted
  156. into the token stream immediately after a line's final token if that token is
  157. <ul>
  158. <li>an
  159. <a href="#Identifiers">identifier</a>
  160. </li>
  161. <li>an
  162. <a href="#Integer_literals">integer</a>,
  163. <a href="#Floating-point_literals">floating-point</a>,
  164. <a href="#Imaginary_literals">imaginary</a>,
  165. <a href="#Rune_literals">rune</a>, or
  166. <a href="#String_literals">string</a> literal
  167. </li>
  168. <li>one of the <a href="#Keywords">keywords</a>
  169. <code>break</code>,
  170. <code>continue</code>,
  171. <code>fallthrough</code>, or
  172. <code>return</code>
  173. </li>
  174. <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a>
  175. <code>++</code>,
  176. <code>--</code>,
  177. <code>)</code>,
  178. <code>]</code>, or
  179. <code>}</code>
  180. </li>
  181. </ul>
  182. </li>
  183. <li>
  184. To allow complex statements to occupy a single line, a semicolon
  185. may be omitted before a closing <code>")"</code> or <code>"}"</code>.
  186. </li>
  187. </ol>
  188. <p>
  189. To reflect idiomatic use, code examples in this document elide semicolons
  190. using these rules.
  191. </p>
  192. <h3 id="Identifiers">Identifiers</h3>
  193. <p>
  194. Identifiers name program entities such as variables and types.
  195. An identifier is a sequence of one or more letters and digits.
  196. The first character in an identifier must be a letter.
  197. </p>
  198. <pre class="ebnf">
  199. identifier = letter { letter | unicode_digit } .
  200. </pre>
  201. <pre>
  202. a
  203. _x9
  204. ThisVariableIsExported
  205. αβ
  206. </pre>
  207. <p>
  208. Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
  209. </p>
  210. <h3 id="Keywords">Keywords</h3>
  211. <p>
  212. The following keywords are reserved and may not be used as identifiers.
  213. </p>
  214. <pre class="grammar">
  215. break default func interface select
  216. case defer go map struct
  217. chan else goto package switch
  218. const fallthrough if range type
  219. continue for import return var
  220. </pre>
  221. <h3 id="Operators_and_punctuation">Operators and punctuation</h3>
  222. <p>
  223. The following character sequences represent <a href="#Operators">operators</a>
  224. (including <a href="#Assignments">assignment operators</a>) and punctuation:
  225. </p>
  226. <pre class="grammar">
  227. + &amp; += &amp;= &amp;&amp; == != ( )
  228. - | -= |= || &lt; &lt;= [ ]
  229. * ^ *= ^= &lt;- &gt; &gt;= { }
  230. / &lt;&lt; /= &lt;&lt;= ++ = := , ;
  231. % &gt;&gt; %= &gt;&gt;= -- ! ... . :
  232. &amp;^ &amp;^=
  233. </pre>
  234. <h3 id="Integer_literals">Integer literals</h3>
  235. <p>
  236. An integer literal is a sequence of digits representing an
  237. <a href="#Constants">integer constant</a>.
  238. An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code>
  239. for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal,
  240. and <code>0x</code> or <code>0X</code> for hexadecimal.
  241. A single <code>0</code> is considered a decimal zero.
  242. In hexadecimal literals, letters <code>a</code> through <code>f</code>
  243. and <code>A</code> through <code>F</code> represent values 10 through 15.
  244. </p>
  245. <p>
  246. For readability, an underscore character <code>_</code> may appear after
  247. a base prefix or between successive digits; such underscores do not change
  248. the literal's value.
  249. </p>
  250. <pre class="ebnf">
  251. int_lit = decimal_lit | binary_lit | octal_lit | hex_lit .
  252. decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
  253. binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits .
  254. octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .
  255. hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits .
  256. decimal_digits = decimal_digit { [ "_" ] decimal_digit } .
  257. binary_digits = binary_digit { [ "_" ] binary_digit } .
  258. octal_digits = octal_digit { [ "_" ] octal_digit } .
  259. hex_digits = hex_digit { [ "_" ] hex_digit } .
  260. </pre>
  261. <pre>
  262. 42
  263. 4_2
  264. 0600
  265. 0_600
  266. 0o600
  267. 0O600 // second character is capital letter 'O'
  268. 0xBadFace
  269. 0xBad_Face
  270. 0x_67_7a_2f_cc_40_c6
  271. 170141183460469231731687303715884105727
  272. 170_141183_460469_231731_687303_715884_105727
  273. _42 // an identifier, not an integer literal
  274. 42_ // invalid: _ must separate successive digits
  275. 4__2 // invalid: only one _ at a time
  276. 0_xBadFace // invalid: _ must separate successive digits
  277. </pre>
  278. <h3 id="Floating-point_literals">Floating-point literals</h3>
  279. <p>
  280. A floating-point literal is a decimal or hexadecimal representation of a
  281. <a href="#Constants">floating-point constant</a>.
  282. </p>
  283. <p>
  284. A decimal floating-point literal consists of an integer part (decimal digits),
  285. a decimal point, a fractional part (decimal digits), and an exponent part
  286. (<code>e</code> or <code>E</code> followed by an optional sign and decimal digits).
  287. One of the integer part or the fractional part may be elided; one of the decimal point
  288. or the exponent part may be elided.
  289. An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>.
  290. </p>
  291. <p>
  292. A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code>
  293. prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),
  294. and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits).
  295. One of the integer part or the fractional part may be elided; the radix point may be elided as well,
  296. but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)
  297. An exponent value exp scales the mantissa (integer and fractional part) by 2<sup>exp</sup>.
  298. </p>
  299. <p>
  300. For readability, an underscore character <code>_</code> may appear after
  301. a base prefix or between successive digits; such underscores do not change
  302. the literal value.
  303. </p>
  304. <pre class="ebnf">
  305. float_lit = decimal_float_lit | hex_float_lit .
  306. decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |
  307. decimal_digits decimal_exponent |
  308. "." decimal_digits [ decimal_exponent ] .
  309. decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .
  310. hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent .
  311. hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] |
  312. [ "_" ] hex_digits |
  313. "." hex_digits .
  314. hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .
  315. </pre>
  316. <pre>
  317. 0.
  318. 72.40
  319. 072.40 // == 72.40
  320. 2.71828
  321. 1.e+0
  322. 6.67428e-11
  323. 1E6
  324. .25
  325. .12345E+5
  326. 1_5. // == 15.0
  327. 0.15e+0_2 // == 15.0
  328. 0x1p-2 // == 0.25
  329. 0x2.p10 // == 2048.0
  330. 0x1.Fp+0 // == 1.9375
  331. 0X.8p-0 // == 0.5
  332. 0X_1FFFP-16 // == 0.1249847412109375
  333. 0x15e-2 // == 0x15e - 2 (integer subtraction)
  334. 0x.p1 // invalid: mantissa has no digits
  335. 1p-2 // invalid: p exponent requires hexadecimal mantissa
  336. 0x1.5e-2 // invalid: hexadecimal mantissa requires p exponent
  337. 1_.5 // invalid: _ must separate successive digits
  338. 1._5 // invalid: _ must separate successive digits
  339. 1.5_e1 // invalid: _ must separate successive digits
  340. 1.5e_1 // invalid: _ must separate successive digits
  341. 1.5e1_ // invalid: _ must separate successive digits
  342. </pre>
  343. <h3 id="Imaginary_literals">Imaginary literals</h3>
  344. <p>
  345. An imaginary literal represents the imaginary part of a
  346. <a href="#Constants">complex constant</a>.
  347. It consists of an <a href="#Integer_literals">integer</a> or
  348. <a href="#Floating-point_literals">floating-point</a> literal
  349. followed by the lower-case letter <code>i</code>.
  350. The value of an imaginary literal is the value of the respective
  351. integer or floating-point literal multiplied by the imaginary unit <i>i</i>.
  352. </p>
  353. <pre class="ebnf">
  354. imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .
  355. </pre>
  356. <p>
  357. For backward compatibility, an imaginary literal's integer part consisting
  358. entirely of decimal digits (and possibly underscores) is considered a decimal
  359. integer, even if it starts with a leading <code>0</code>.
  360. </p>
  361. <pre>
  362. 0i
  363. 0123i // == 123i for backward-compatibility
  364. 0o123i // == 0o123 * 1i == 83i
  365. 0xabci // == 0xabc * 1i == 2748i
  366. 0.i
  367. 2.71828i
  368. 1.e+0i
  369. 6.67428e-11i
  370. 1E6i
  371. .25i
  372. .12345E+5i
  373. 0x1p-2i // == 0x1p-2 * 1i == 0.25i
  374. </pre>
  375. <h3 id="Rune_literals">Rune literals</h3>
  376. <p>
  377. A rune literal represents a <a href="#Constants">rune constant</a>,
  378. an integer value identifying a Unicode code point.
  379. A rune literal is expressed as one or more characters enclosed in single quotes,
  380. as in <code>'x'</code> or <code>'\n'</code>.
  381. Within the quotes, any character may appear except newline and unescaped single
  382. quote. A single quoted character represents the Unicode value
  383. of the character itself,
  384. while multi-character sequences beginning with a backslash encode
  385. values in various formats.
  386. </p>
  387. <p>
  388. The simplest form represents the single character within the quotes;
  389. since Go source text is Unicode characters encoded in UTF-8, multiple
  390. UTF-8-encoded bytes may represent a single integer value. For
  391. instance, the literal <code>'a'</code> holds a single byte representing
  392. a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
  393. <code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
  394. a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
  395. </p>
  396. <p>
  397. Several backslash escapes allow arbitrary values to be encoded as
  398. ASCII text. There are four ways to represent the integer value
  399. as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
  400. digits; <code>\u</code> followed by exactly four hexadecimal digits;
  401. <code>\U</code> followed by exactly eight hexadecimal digits, and a
  402. plain backslash <code>\</code> followed by exactly three octal digits.
  403. In each case the value of the literal is the value represented by
  404. the digits in the corresponding base.
  405. </p>
  406. <p>
  407. Although these representations all result in an integer, they have
  408. different valid ranges. Octal escapes must represent a value between
  409. 0 and 255 inclusive. Hexadecimal escapes satisfy this condition
  410. by construction. The escapes <code>\u</code> and <code>\U</code>
  411. represent Unicode code points so within them some values are illegal,
  412. in particular those above <code>0x10FFFF</code> and surrogate halves.
  413. </p>
  414. <p>
  415. After a backslash, certain single-character escapes represent special values:
  416. </p>
  417. <pre class="grammar">
  418. \a U+0007 alert or bell
  419. \b U+0008 backspace
  420. \f U+000C form feed
  421. \n U+000A line feed or newline
  422. \r U+000D carriage return
  423. \t U+0009 horizontal tab
  424. \v U+000B vertical tab
  425. \\ U+005C backslash
  426. \' U+0027 single quote (valid escape only within rune literals)
  427. \" U+0022 double quote (valid escape only within string literals)
  428. </pre>
  429. <p>
  430. All other sequences starting with a backslash are illegal inside rune literals.
  431. </p>
  432. <pre class="ebnf">
  433. rune_lit = "'" ( unicode_value | byte_value ) "'" .
  434. unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
  435. byte_value = octal_byte_value | hex_byte_value .
  436. octal_byte_value = `\` octal_digit octal_digit octal_digit .
  437. hex_byte_value = `\` "x" hex_digit hex_digit .
  438. little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
  439. big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
  440. hex_digit hex_digit hex_digit hex_digit .
  441. escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
  442. </pre>
  443. <pre>
  444. 'a'
  445. 'ä'
  446. '本'
  447. '\t'
  448. '\000'
  449. '\007'
  450. '\377'
  451. '\x07'
  452. '\xff'
  453. '\u12e4'
  454. '\U00101234'
  455. '\'' // rune literal containing single quote character
  456. 'aa' // illegal: too many characters
  457. '\xa' // illegal: too few hexadecimal digits
  458. '\0' // illegal: too few octal digits
  459. '\uDFFF' // illegal: surrogate half
  460. '\U00110000' // illegal: invalid Unicode code point
  461. </pre>
  462. <h3 id="String_literals">String literals</h3>
  463. <p>
  464. A string literal represents a <a href="#Constants">string constant</a>
  465. obtained from concatenating a sequence of characters. There are two forms:
  466. raw string literals and interpreted string literals.
  467. </p>
  468. <p>
  469. Raw string literals are character sequences between back quotes, as in
  470. <code>`foo`</code>. Within the quotes, any character may appear except
  471. back quote. The value of a raw string literal is the
  472. string composed of the uninterpreted (implicitly UTF-8-encoded) characters
  473. between the quotes;
  474. in particular, backslashes have no special meaning and the string may
  475. contain newlines.
  476. Carriage return characters ('\r') inside raw string literals
  477. are discarded from the raw string value.
  478. </p>
  479. <p>
  480. Interpreted string literals are character sequences between double
  481. quotes, as in <code>&quot;bar&quot;</code>.
  482. Within the quotes, any character may appear except newline and unescaped double quote.
  483. The text between the quotes forms the
  484. value of the literal, with backslash escapes interpreted as they
  485. are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
  486. <code>\"</code> is legal), with the same restrictions.
  487. The three-digit octal (<code>\</code><i>nnn</i>)
  488. and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
  489. <i>bytes</i> of the resulting string; all other escapes represent
  490. the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
  491. Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
  492. a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
  493. <code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
  494. the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
  495. U+00FF.
  496. </p>
  497. <pre class="ebnf">
  498. string_lit = raw_string_lit | interpreted_string_lit .
  499. raw_string_lit = "`" { unicode_char | newline } "`" .
  500. interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
  501. </pre>
  502. <pre>
  503. `abc` // same as "abc"
  504. `\n
  505. \n` // same as "\\n\n\\n"
  506. "\n"
  507. "\"" // same as `"`
  508. "Hello, world!\n"
  509. "日本語"
  510. "\u65e5本\U00008a9e"
  511. "\xff\u00FF"
  512. "\uD800" // illegal: surrogate half
  513. "\U00110000" // illegal: invalid Unicode code point
  514. </pre>
  515. <p>
  516. These examples all represent the same string:
  517. </p>
  518. <pre>
  519. "日本語" // UTF-8 input text
  520. `日本語` // UTF-8 input text as a raw literal
  521. "\u65e5\u672c\u8a9e" // the explicit Unicode code points
  522. "\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
  523. "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
  524. </pre>
  525. <p>
  526. If the source code represents a character as two code points, such as
  527. a combining form involving an accent and a letter, the result will be
  528. an error if placed in a rune literal (it is not a single code
  529. point), and will appear as two code points if placed in a string
  530. literal.
  531. </p>
  532. <h2 id="Constants">Constants</h2>
  533. <p>There are <i>boolean constants</i>,
  534. <i>rune constants</i>,
  535. <i>integer constants</i>,
  536. <i>floating-point constants</i>, <i>complex constants</i>,
  537. and <i>string constants</i>. Rune, integer, floating-point,
  538. and complex constants are
  539. collectively called <i>numeric constants</i>.
  540. </p>
  541. <p>
  542. A constant value is represented by a
  543. <a href="#Rune_literals">rune</a>,
  544. <a href="#Integer_literals">integer</a>,
  545. <a href="#Floating-point_literals">floating-point</a>,
  546. <a href="#Imaginary_literals">imaginary</a>,
  547. or
  548. <a href="#String_literals">string</a> literal,
  549. an identifier denoting a constant,
  550. a <a href="#Constant_expressions">constant expression</a>,
  551. a <a href="#Conversions">conversion</a> with a result that is a constant, or
  552. the result value of some built-in functions such as
  553. <code>unsafe.Sizeof</code> applied to any value,
  554. <code>cap</code> or <code>len</code> applied to
  555. <a href="#Length_and_capacity">some expressions</a>,
  556. <code>real</code> and <code>imag</code> applied to a complex constant
  557. and <code>complex</code> applied to numeric constants.
  558. The boolean truth values are represented by the predeclared constants
  559. <code>true</code> and <code>false</code>. The predeclared identifier
  560. <a href="#Iota">iota</a> denotes an integer constant.
  561. </p>
  562. <p>
  563. In general, complex constants are a form of
  564. <a href="#Constant_expressions">constant expression</a>
  565. and are discussed in that section.
  566. </p>
  567. <p>
  568. Numeric constants represent exact values of arbitrary precision and do not overflow.
  569. Consequently, there are no constants denoting the IEEE 754 negative zero, infinity,
  570. and not-a-number values.
  571. </p>
  572. <p>
  573. Constants may be <a href="#Types">typed</a> or <i>untyped</i>.
  574. Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
  575. and certain <a href="#Constant_expressions">constant expressions</a>
  576. containing only untyped constant operands are untyped.
  577. </p>
  578. <p>
  579. A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
  580. or <a href="#Conversions">conversion</a>, or implicitly when used in a
  581. <a href="#Variable_declarations">variable declaration</a> or an
  582. <a href="#Assignments">assignment</a> or as an
  583. operand in an <a href="#Expressions">expression</a>.
  584. It is an error if the constant value
  585. cannot be <a href="#Representability">represented</a> as a value of the respective type.
  586. </p>
  587. <p>
  588. An untyped constant has a <i>default type</i> which is the type to which the
  589. constant is implicitly converted in contexts where a typed value is required,
  590. for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>
  591. such as <code>i := 0</code> where there is no explicit type.
  592. The default type of an untyped constant is <code>bool</code>, <code>rune</code>,
  593. <code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code>
  594. respectively, depending on whether it is a boolean, rune, integer, floating-point,
  595. complex, or string constant.
  596. </p>
  597. <p>
  598. Implementation restriction: Although numeric constants have arbitrary
  599. precision in the language, a compiler may implement them using an
  600. internal representation with limited precision. That said, every
  601. implementation must:
  602. </p>
  603. <ul>
  604. <li>Represent integer constants with at least 256 bits.</li>
  605. <li>Represent floating-point constants, including the parts of
  606. a complex constant, with a mantissa of at least 256 bits
  607. and a signed binary exponent of at least 16 bits.</li>
  608. <li>Give an error if unable to represent an integer constant
  609. precisely.</li>
  610. <li>Give an error if unable to represent a floating-point or
  611. complex constant due to overflow.</li>
  612. <li>Round to the nearest representable constant if unable to
  613. represent a floating-point or complex constant due to limits
  614. on precision.</li>
  615. </ul>
  616. <p>
  617. These requirements apply both to literal constants and to the result
  618. of evaluating <a href="#Constant_expressions">constant
  619. expressions</a>.
  620. </p>
  621. <h2 id="Variables">Variables</h2>
  622. <p>
  623. A variable is a storage location for holding a <i>value</i>.
  624. The set of permissible values is determined by the
  625. variable's <i><a href="#Types">type</a></i>.
  626. </p>
  627. <p>
  628. A <a href="#Variable_declarations">variable declaration</a>
  629. or, for function parameters and results, the signature
  630. of a <a href="#Function_declarations">function declaration</a>
  631. or <a href="#Function_literals">function literal</a> reserves
  632. storage for a named variable.
  633. Calling the built-in function <a href="#Allocation"><code>new</code></a>
  634. or taking the address of a <a href="#Composite_literals">composite literal</a>
  635. allocates storage for a variable at run time.
  636. Such an anonymous variable is referred to via a (possibly implicit)
  637. <a href="#Address_operators">pointer indirection</a>.
  638. </p>
  639. <p>
  640. <i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,
  641. and <a href="#Struct_types">struct</a> types have elements and fields that may
  642. be <a href="#Address_operators">addressed</a> individually. Each such element
  643. acts like a variable.
  644. </p>
  645. <p>
  646. The <i>static type</i> (or just <i>type</i>) of a variable is the
  647. type given in its declaration, the type provided in the
  648. <code>new</code> call or composite literal, or the type of
  649. an element of a structured variable.
  650. Variables of interface type also have a distinct <i>dynamic type</i>,
  651. which is the concrete type of the value assigned to the variable at run time
  652. (unless the value is the predeclared identifier <code>nil</code>,
  653. which has no type).
  654. The dynamic type may vary during execution but values stored in interface
  655. variables are always <a href="#Assignability">assignable</a>
  656. to the static type of the variable.
  657. </p>
  658. <pre>
  659. var x interface{} // x is nil and has static type interface{}
  660. var v *T // v has value nil, static type *T
  661. x = 42 // x has value 42 and dynamic type int
  662. x = v // x has value (*T)(nil) and dynamic type *T
  663. </pre>
  664. <p>
  665. A variable's value is retrieved by referring to the variable in an
  666. <a href="#Expressions">expression</a>; it is the most recent value
  667. <a href="#Assignments">assigned</a> to the variable.
  668. If a variable has not yet been assigned a value, its value is the
  669. <a href="#The_zero_value">zero value</a> for its type.
  670. </p>
  671. <h2 id="Types">Types</h2>
  672. <p>
  673. A type determines a set of values together with operations and methods specific
  674. to those values. A type may be denoted by a <i>type name</i>, if it has one,
  675. or specified using a <i>type literal</i>, which composes a type from existing types.
  676. </p>
  677. <pre class="ebnf">
  678. Type = TypeName | TypeLit | "(" Type ")" .
  679. TypeName = identifier | QualifiedIdent .
  680. TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
  681. SliceType | MapType | ChannelType .
  682. </pre>
  683. <p>
  684. The language <a href="#Predeclared_identifiers">predeclares</a> certain type names.
  685. Others are introduced with <a href="#Type_declarations">type declarations</a>.
  686. <i>Composite types</i>&mdash;array, struct, pointer, function,
  687. interface, slice, map, and channel types&mdash;may be constructed using
  688. type literals.
  689. </p>
  690. <p>
  691. Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
  692. is one of the predeclared boolean, numeric, or string types, or a type literal,
  693. the corresponding underlying
  694. type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type
  695. is the underlying type of the type to which <code>T</code> refers in its
  696. <a href="#Type_declarations">type declaration</a>.
  697. </p>
  698. <pre>
  699. type (
  700. A1 = string
  701. A2 = A1
  702. )
  703. type (
  704. B1 string
  705. B2 B1
  706. B3 []B1
  707. B4 B3
  708. )
  709. </pre>
  710. <p>
  711. The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>,
  712. and <code>B2</code> is <code>string</code>.
  713. The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>.
  714. </p>
  715. <h3 id="Method_sets">Method sets</h3>
  716. <p>
  717. A type has a (possibly empty) <i>method set</i> associated with it.
  718. The method set of an <a href="#Interface_types">interface type</a> is its interface.
  719. The method set of any other type <code>T</code> consists of all
  720. <a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
  721. The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code>
  722. is the set of all methods declared with receiver <code>*T</code> or <code>T</code>
  723. (that is, it also contains the method set of <code>T</code>).
  724. Further rules apply to structs containing embedded fields, as described
  725. in the section on <a href="#Struct_types">struct types</a>.
  726. Any other type has an empty method set.
  727. In a method set, each method must have a
  728. <a href="#Uniqueness_of_identifiers">unique</a>
  729. non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
  730. </p>
  731. <p>
  732. The method set of a type determines the interfaces that the
  733. type <a href="#Interface_types">implements</a>
  734. and the methods that can be <a href="#Calls">called</a>
  735. using a receiver of that type.
  736. </p>
  737. <h3 id="Boolean_types">Boolean types</h3>
  738. <p>
  739. A <i>boolean type</i> represents the set of Boolean truth values
  740. denoted by the predeclared constants <code>true</code>
  741. and <code>false</code>. The predeclared boolean type is <code>bool</code>;
  742. it is a <a href="#Type_definitions">defined type</a>.
  743. </p>
  744. <h3 id="Numeric_types">Numeric types</h3>
  745. <p>
  746. A <i>numeric type</i> represents sets of integer or floating-point values.
  747. The predeclared architecture-independent numeric types are:
  748. </p>
  749. <pre class="grammar">
  750. uint8 the set of all unsigned 8-bit integers (0 to 255)
  751. uint16 the set of all unsigned 16-bit integers (0 to 65535)
  752. uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
  753. uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
  754. int8 the set of all signed 8-bit integers (-128 to 127)
  755. int16 the set of all signed 16-bit integers (-32768 to 32767)
  756. int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
  757. int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
  758. float32 the set of all IEEE 754 32-bit floating-point numbers
  759. float64 the set of all IEEE 754 64-bit floating-point numbers
  760. complex64 the set of all complex numbers with float32 real and imaginary parts
  761. complex128 the set of all complex numbers with float64 real and imaginary parts
  762. byte alias for uint8
  763. rune alias for int32
  764. </pre>
  765. <p>
  766. The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
  767. <a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
  768. </p>
  769. <p>
  770. There is also a set of predeclared numeric types with implementation-specific sizes:
  771. </p>
  772. <pre class="grammar">
  773. uint either 32 or 64 bits
  774. int same size as uint
  775. uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
  776. </pre>
  777. <p>
  778. To avoid portability issues all numeric types are <a href="#Type_definitions">defined
  779. types</a> and thus distinct except
  780. <code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and
  781. <code>rune</code>, which is an alias for <code>int32</code>.
  782. Explicit conversions
  783. are required when different numeric types are mixed in an expression
  784. or assignment. For instance, <code>int32</code> and <code>int</code>
  785. are not the same type even though they may have the same size on a
  786. particular architecture.
  787. </p>
  788. <h3 id="String_types">String types</h3>
  789. <p>
  790. A <i>string type</i> represents the set of string values.
  791. A string value is a (possibly empty) sequence of bytes.
  792. The number of bytes is called the length of the string and is never negative.
  793. Strings are immutable: once created,
  794. it is impossible to change the contents of a string.
  795. The predeclared string type is <code>string</code>;
  796. it is a <a href="#Type_definitions">defined type</a>.
  797. </p>
  798. <p>
  799. The length of a string <code>s</code> can be discovered using
  800. the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
  801. The length is a compile-time constant if the string is a constant.
  802. A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
  803. 0 through <code>len(s)-1</code>.
  804. It is illegal to take the address of such an element; if
  805. <code>s[i]</code> is the <code>i</code>'th byte of a
  806. string, <code>&amp;s[i]</code> is invalid.
  807. </p>
  808. <h3 id="Array_types">Array types</h3>
  809. <p>
  810. An array is a numbered sequence of elements of a single
  811. type, called the element type.
  812. The number of elements is called the length of the array and is never negative.
  813. </p>
  814. <pre class="ebnf">
  815. ArrayType = "[" ArrayLength "]" ElementType .
  816. ArrayLength = Expression .
  817. ElementType = Type .
  818. </pre>
  819. <p>
  820. The length is part of the array's type; it must evaluate to a
  821. non-negative <a href="#Constants">constant</a>
  822. <a href="#Representability">representable</a> by a value
  823. of type <code>int</code>.
  824. The length of array <code>a</code> can be discovered
  825. using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
  826. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
  827. 0 through <code>len(a)-1</code>.
  828. Array types are always one-dimensional but may be composed to form
  829. multi-dimensional types.
  830. </p>
  831. <pre>
  832. [32]byte
  833. [2*N] struct { x, y int32 }
  834. [1000]*float64
  835. [3][5]int
  836. [2][2][2]float64 // same as [2]([2]([2]float64))
  837. </pre>
  838. <h3 id="Slice_types">Slice types</h3>
  839. <p>
  840. A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
  841. provides access to a numbered sequence of elements from that array.
  842. A slice type denotes the set of all slices of arrays of its element type.
  843. The number of elements is called the length of the slice and is never negative.
  844. The value of an uninitialized slice is <code>nil</code>.
  845. </p>
  846. <pre class="ebnf">
  847. SliceType = "[" "]" ElementType .
  848. </pre>
  849. <p>
  850. The length of a slice <code>s</code> can be discovered by the built-in function
  851. <a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
  852. execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
  853. 0 through <code>len(s)-1</code>. The slice index of a
  854. given element may be less than the index of the same element in the
  855. underlying array.
  856. </p>
  857. <p>
  858. A slice, once initialized, is always associated with an underlying
  859. array that holds its elements. A slice therefore shares storage
  860. with its array and with other slices of the same array; by contrast,
  861. distinct arrays always represent distinct storage.
  862. </p>
  863. <p>
  864. The array underlying a slice may extend past the end of the slice.
  865. The <i>capacity</i> is a measure of that extent: it is the sum of
  866. the length of the slice and the length of the array beyond the slice;
  867. a slice of length up to that capacity can be created by
  868. <a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
  869. The capacity of a slice <code>a</code> can be discovered using the
  870. built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
  871. </p>
  872. <p>
  873. A new, initialized slice value for a given element type <code>T</code> is
  874. made using the built-in function
  875. <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
  876. which takes a slice type
  877. and parameters specifying the length and optionally the capacity.
  878. A slice created with <code>make</code> always allocates a new, hidden array
  879. to which the returned slice value refers. That is, executing
  880. </p>
  881. <pre>
  882. make([]T, length, capacity)
  883. </pre>
  884. <p>
  885. produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
  886. it, so these two expressions are equivalent:
  887. </p>
  888. <pre>
  889. make([]int, 50, 100)
  890. new([100]int)[0:50]
  891. </pre>
  892. <p>
  893. Like arrays, slices are always one-dimensional but may be composed to construct
  894. higher-dimensional objects.
  895. With arrays of arrays, the inner arrays are, by construction, always the same length;
  896. however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
  897. Moreover, the inner slices must be initialized individually.
  898. </p>
  899. <h3 id="Struct_types">Struct types</h3>
  900. <p>
  901. A struct is a sequence of named elements, called fields, each of which has a
  902. name and a type. Field names may be specified explicitly (IdentifierList) or
  903. implicitly (EmbeddedField).
  904. Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
  905. be <a href="#Uniqueness_of_identifiers">unique</a>.
  906. </p>
  907. <pre class="ebnf">
  908. StructType = "struct" "{" { FieldDecl ";" } "}" .
  909. FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .
  910. EmbeddedField = [ "*" ] TypeName .
  911. Tag = string_lit .
  912. </pre>
  913. <pre>
  914. // An empty struct.
  915. struct {}
  916. // A struct with 6 fields.
  917. struct {
  918. x, y int
  919. u float32
  920. _ float32 // padding
  921. A *[]int
  922. F func()
  923. }
  924. </pre>
  925. <p>
  926. A field declared with a type but no explicit field name is called an <i>embedded field</i>.
  927. An embedded field must be specified as
  928. a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
  929. and <code>T</code> itself may not be
  930. a pointer type. The unqualified type name acts as the field name.
  931. </p>
  932. <pre>
  933. // A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
  934. struct {
  935. T1 // field name is T1
  936. *T2 // field name is T2
  937. P.T3 // field name is T3
  938. *P.T4 // field name is T4
  939. x, y int // field names are x and y
  940. }
  941. </pre>
  942. <p>
  943. The following declaration is illegal because field names must be unique
  944. in a struct type:
  945. </p>
  946. <pre>
  947. struct {
  948. T // conflicts with embedded field *T and *P.T
  949. *T // conflicts with embedded field T and *P.T
  950. *P.T // conflicts with embedded field T and *T
  951. }
  952. </pre>
  953. <p>
  954. A field or <a href="#Method_declarations">method</a> <code>f</code> of an
  955. embedded field in a struct <code>x</code> is called <i>promoted</i> if
  956. <code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
  957. that field or method <code>f</code>.
  958. </p>
  959. <p>
  960. Promoted fields act like ordinary fields
  961. of a struct except that they cannot be used as field names in
  962. <a href="#Composite_literals">composite literals</a> of the struct.
  963. </p>
  964. <p>
  965. Given a struct type <code>S</code> and a <a href="#Type_definitions">defined type</a>
  966. <code>T</code>, promoted methods are included in the method set of the struct as follows:
  967. </p>
  968. <ul>
  969. <li>
  970. If <code>S</code> contains an embedded field <code>T</code>,
  971. the <a href="#Method_sets">method sets</a> of <code>S</code>
  972. and <code>*S</code> both include promoted methods with receiver
  973. <code>T</code>. The method set of <code>*S</code> also
  974. includes promoted methods with receiver <code>*T</code>.
  975. </li>
  976. <li>
  977. If <code>S</code> contains an embedded field <code>*T</code>,
  978. the method sets of <code>S</code> and <code>*S</code> both
  979. include promoted methods with receiver <code>T</code> or
  980. <code>*T</code>.
  981. </li>
  982. </ul>
  983. <p>
  984. A field declaration may be followed by an optional string literal <i>tag</i>,
  985. which becomes an attribute for all the fields in the corresponding
  986. field declaration. An empty tag string is equivalent to an absent tag.
  987. The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
  988. and take part in <a href="#Type_identity">type identity</a> for structs
  989. but are otherwise ignored.
  990. </p>
  991. <pre>
  992. struct {
  993. x, y float64 "" // an empty tag string is like an absent tag
  994. name string "any string is permitted as a tag"
  995. _ [4]byte "ceci n'est pas un champ de structure"
  996. }
  997. // A struct corresponding to a TimeStamp protocol buffer.
  998. // The tag strings define the protocol buffer field numbers;
  999. // they follow the convention outlined by the reflect package.
  1000. struct {
  1001. microsec uint64 `protobuf:"1"`
  1002. serverIP6 uint64 `protobuf:"2"`
  1003. }
  1004. </pre>
  1005. <h3 id="Pointer_types">Pointer types</h3>
  1006. <p>
  1007. A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
  1008. type, called the <i>base type</i> of the pointer.
  1009. The value of an uninitialized pointer is <code>nil</code>.
  1010. </p>
  1011. <pre class="ebnf">
  1012. PointerType = "*" BaseType .
  1013. BaseType = Type .
  1014. </pre>
  1015. <pre>
  1016. *Point
  1017. *[4]int
  1018. </pre>
  1019. <h3 id="Function_types">Function types</h3>
  1020. <p>
  1021. A function type denotes the set of all functions with the same parameter
  1022. and result types. The value of an uninitialized variable of function type
  1023. is <code>nil</code>.
  1024. </p>
  1025. <pre class="ebnf">
  1026. FunctionType = "func" Signature .
  1027. Signature = Parameters [ Result ] .
  1028. Result = Parameters | Type .
  1029. Parameters = "(" [ ParameterList [ "," ] ] ")" .
  1030. ParameterList = ParameterDecl { "," ParameterDecl } .
  1031. ParameterDecl = [ IdentifierList ] [ "..." ] Type .
  1032. </pre>
  1033. <p>
  1034. Within a list of parameters or results, the names (IdentifierList)
  1035. must either all be present or all be absent. If present, each name
  1036. stands for one item (parameter or result) of the specified type and
  1037. all non-<a href="#Blank_identifier">blank</a> names in the signature
  1038. must be <a href="#Uniqueness_of_identifiers">unique</a>.
  1039. If absent, each type stands for one item of that type.
  1040. Parameter and result
  1041. lists are always parenthesized except that if there is exactly
  1042. one unnamed result it may be written as an unparenthesized type.
  1043. </p>
  1044. <p>
  1045. The final incoming parameter in a function signature may have
  1046. a type prefixed with <code>...</code>.
  1047. A function with such a parameter is called <i>variadic</i> and
  1048. may be invoked with zero or more arguments for that parameter.
  1049. </p>
  1050. <pre>
  1051. func()
  1052. func(x int) int
  1053. func(a, _ int, z float32) bool
  1054. func(a, b int, z float32) (bool)
  1055. func(prefix string, values ...int)
  1056. func(a, b int, z float64, opt ...interface{}) (success bool)
  1057. func(int, int, float64) (float64, *[]int)
  1058. func(n int) func(p *T)
  1059. </pre>
  1060. <h3 id="Interface_types">Interface types</h3>
  1061. <p>
  1062. An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>.
  1063. A variable of interface type can store a value of any type with a method set
  1064. that is any superset of the interface. Such a type is said to
  1065. <i>implement the interface</i>.
  1066. The value of an uninitialized variable of interface type is <code>nil</code>.
  1067. </p>
  1068. <pre class="ebnf">
  1069. InterfaceType = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .
  1070. MethodSpec = MethodName Signature .
  1071. MethodName = identifier .
  1072. InterfaceTypeName = TypeName .
  1073. </pre>
  1074. <p>
  1075. An interface type may specify methods <i>explicitly</i> through method specifications,
  1076. or it may <i>embed</i> methods of other interfaces through interface type names.
  1077. </p>
  1078. <pre>
  1079. // A simple File interface.
  1080. interface {
  1081. Read([]byte) (int, error)
  1082. Write([]byte) (int, error)
  1083. Close() error
  1084. }
  1085. </pre>
  1086. <p>
  1087. The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a>
  1088. and not <a href="#Blank_identifier">blank</a>.
  1089. </p>
  1090. <pre>
  1091. interface {
  1092. String() string
  1093. String() string // illegal: String not unique
  1094. _(x int) // illegal: method must have non-blank name
  1095. }
  1096. </pre>
  1097. <p>
  1098. More than one type may implement an interface.
  1099. For instance, if two types <code>S1</code> and <code>S2</code>
  1100. have the method set
  1101. </p>
  1102. <pre>
  1103. func (p T) Read(p []byte) (n int, err error)
  1104. func (p T) Write(p []byte) (n int, err error)
  1105. func (p T) Close() error
  1106. </pre>
  1107. <p>
  1108. (where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
  1109. then the <code>File</code> interface is implemented by both <code>S1</code> and
  1110. <code>S2</code>, regardless of what other methods
  1111. <code>S1</code> and <code>S2</code> may have or share.
  1112. </p>
  1113. <p>
  1114. A type implements any interface comprising any subset of its methods
  1115. and may therefore implement several distinct interfaces. For
  1116. instance, all types implement the <i>empty interface</i>:
  1117. </p>
  1118. <pre>
  1119. interface{}
  1120. </pre>
  1121. <p>
  1122. Similarly, consider this interface specification,
  1123. which appears within a <a href="#Type_declarations">type declaration</a>
  1124. to define an interface called <code>Locker</code>:
  1125. </p>
  1126. <pre>
  1127. type Locker interface {
  1128. Lock()
  1129. Unlock()
  1130. }
  1131. </pre>
  1132. <p>
  1133. If <code>S1</code> and <code>S2</code> also implement
  1134. </p>
  1135. <pre>
  1136. func (p T) Lock() { … }
  1137. func (p T) Unlock() { … }
  1138. </pre>
  1139. <p>
  1140. they implement the <code>Locker</code> interface as well
  1141. as the <code>File</code> interface.
  1142. </p>
  1143. <p>
  1144. An interface <code>T</code> may use a (possibly qualified) interface type
  1145. name <code>E</code> in place of a method specification. This is called
  1146. <i>embedding</i> interface <code>E</code> in <code>T</code>.
  1147. The <a href="#Method_sets">method set</a> of <code>T</code> is the <i>union</i>
  1148. of the method sets of <code>T</code>’s explicitly declared methods and of
  1149. <code>T</code>’s embedded interfaces.
  1150. </p>
  1151. <pre>
  1152. type Reader interface {
  1153. Read(p []byte) (n int, err error)
  1154. Close() error
  1155. }
  1156. type Writer interface {
  1157. Write(p []byte) (n int, err error)
  1158. Close() error
  1159. }
  1160. // ReadWriter's methods are Read, Write, and Close.
  1161. type ReadWriter interface {
  1162. Reader // includes methods of Reader in ReadWriter's method set
  1163. Writer // includes methods of Writer in ReadWriter's method set
  1164. }
  1165. </pre>
  1166. <p>
  1167. A <i>union</i> of method sets contains the (exported and non-exported)
  1168. methods of each method set exactly once, and methods with the
  1169. <a href="#Uniqueness_of_identifiers">same</a> names must
  1170. have <a href="#Type_identity">identical</a> signatures.
  1171. </p>
  1172. <pre>
  1173. type ReadCloser interface {
  1174. Reader // includes methods of Reader in ReadCloser's method set
  1175. Close() // illegal: signatures of Reader.Close and Close are different
  1176. }
  1177. </pre>
  1178. <p>
  1179. An interface type <code>T</code> may not embed itself
  1180. or any interface type that embeds <code>T</code>, recursively.
  1181. </p>
  1182. <pre>
  1183. // illegal: Bad cannot embed itself
  1184. type Bad interface {
  1185. Bad
  1186. }
  1187. // illegal: Bad1 cannot embed itself using Bad2
  1188. type Bad1 interface {
  1189. Bad2
  1190. }
  1191. type Bad2 interface {
  1192. Bad1
  1193. }
  1194. </pre>
  1195. <h3 id="Map_types">Map types</h3>
  1196. <p>
  1197. A map is an unordered group of elements of one type, called the
  1198. element type, indexed by a set of unique <i>keys</i> of another type,
  1199. called the key type.
  1200. The value of an uninitialized map is <code>nil</code>.
  1201. </p>
  1202. <pre class="ebnf">
  1203. MapType = "map" "[" KeyType "]" ElementType .
  1204. KeyType = Type .
  1205. </pre>
  1206. <p>
  1207. The <a href="#Comparison_operators">comparison operators</a>
  1208. <code>==</code> and <code>!=</code> must be fully defined
  1209. for operands of the key type; thus the key type must not be a function, map, or
  1210. slice.
  1211. If the key type is an interface type, these
  1212. comparison operators must be defined for the dynamic key values;
  1213. failure will cause a <a href="#Run_time_panics">run-time panic</a>.
  1214. </p>
  1215. <pre>
  1216. map[string]int
  1217. map[*T]struct{ x, y float64 }
  1218. map[string]interface{}
  1219. </pre>
  1220. <p>
  1221. The number of map elements is called its length.
  1222. For a map <code>m</code>, it can be discovered using the
  1223. built-in function <a href="#Length_and_capacity"><code>len</code></a>
  1224. and may change during execution. Elements may be added during execution
  1225. using <a href="#Assignments">assignments</a> and retrieved with
  1226. <a href="#Index_expressions">index expressions</a>; they may be removed with the
  1227. <a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
  1228. </p>
  1229. <p>
  1230. A new, empty map value is made using the built-in
  1231. function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
  1232. which takes the map type and an optional capacity hint as arguments:
  1233. </p>
  1234. <pre>
  1235. make(map[string]int)
  1236. make(map[string]int, 100)
  1237. </pre>
  1238. <p>
  1239. The initial capacity does not bound its size:
  1240. maps grow to accommodate the number of items
  1241. stored in them, with the exception of <code>nil</code> maps.
  1242. A <code>nil</code> map is equivalent to an empty map except that no elements
  1243. may be added.
  1244. </p>
  1245. <h3 id="Channel_types">Channel types</h3>
  1246. <p>
  1247. A channel provides a mechanism for
  1248. <a href="#Go_statements">concurrently executing functions</a>
  1249. to communicate by
  1250. <a href="#Send_statements">sending</a> and
  1251. <a href="#Receive_operator">receiving</a>
  1252. values of a specified element type.
  1253. The value of an uninitialized channel is <code>nil</code>.
  1254. </p>
  1255. <pre class="ebnf">
  1256. ChannelType = ( "chan" | "chan" "&lt;-" | "&lt;-" "chan" ) ElementType .
  1257. </pre>
  1258. <p>
  1259. The optional <code>&lt;-</code> operator specifies the channel <i>direction</i>,
  1260. <i>send</i> or <i>receive</i>. If no direction is given, the channel is
  1261. <i>bidirectional</i>.
  1262. A channel may be constrained only to send or only to receive by
  1263. <a href="#Assignments">assignment</a> or
  1264. explicit <a href="#Conversions">conversion</a>.
  1265. </p>
  1266. <pre>
  1267. chan T // can be used to send and receive values of type T
  1268. chan&lt;- float64 // can only be used to send float64s
  1269. &lt;-chan int // can only be used to receive ints
  1270. </pre>
  1271. <p>
  1272. The <code>&lt;-</code> operator associates with the leftmost <code>chan</code>
  1273. possible:
  1274. </p>
  1275. <pre>
  1276. chan&lt;- chan int // same as chan&lt;- (chan int)
  1277. chan&lt;- &lt;-chan int // same as chan&lt;- (&lt;-chan int)
  1278. &lt;-chan &lt;-chan int // same as &lt;-chan (&lt;-chan int)
  1279. chan (&lt;-chan int)
  1280. </pre>
  1281. <p>
  1282. A new, initialized channel
  1283. value can be made using the built-in function
  1284. <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
  1285. which takes the channel type and an optional <i>capacity</i> as arguments:
  1286. </p>
  1287. <pre>
  1288. make(chan int, 100)
  1289. </pre>
  1290. <p>
  1291. The capacity, in number of elements, sets the size of the buffer in the channel.
  1292. If the capacity is zero or absent, the channel is unbuffered and communication
  1293. succeeds only when both a sender and receiver are ready. Otherwise, the channel
  1294. is buffered and communication succeeds without blocking if the buffer
  1295. is not full (sends) or not empty (receives).
  1296. A <code>nil</code> channel is never ready for communication.
  1297. </p>
  1298. <p>
  1299. A channel may be closed with the built-in function
  1300. <a href="#Close"><code>close</code></a>.
  1301. The multi-valued assignment form of the
  1302. <a href="#Receive_operator">receive operator</a>
  1303. reports whether a received value was sent before
  1304. the channel was closed.
  1305. </p>
  1306. <p>
  1307. A single channel may be used in
  1308. <a href="#Send_statements">send statements</a>,
  1309. <a href="#Receive_operator">receive operations</a>,
  1310. and calls to the built-in functions
  1311. <a href="#Length_and_capacity"><code>cap</code></a> and
  1312. <a href="#Length_and_capacity"><code>len</code></a>
  1313. by any number of goroutines without further synchronization.
  1314. Channels act as first-in-first-out queues.
  1315. For example, if one goroutine sends values on a channel
  1316. and a second goroutine receives them, the values are
  1317. received in the order sent.
  1318. </p>
  1319. <h2 id="Properties_of_types_and_values">Properties of types and values</h2>
  1320. <h3 id="Type_identity">Type identity</h3>
  1321. <p>
  1322. Two types are either <i>identical</i> or <i>different</i>.
  1323. </p>
  1324. <p>
  1325. A <a href="#Type_definitions">defined type</a> is always different from any other type.
  1326. Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are
  1327. structurally equivalent; that is, they have the same literal structure and corresponding
  1328. components have identical types. In detail:
  1329. </p>
  1330. <ul>
  1331. <li>Two array types are identical if they have identical element types and
  1332. the same array length.</li>
  1333. <li>Two slice types are identical if they have identical element types.</li>
  1334. <li>Two struct types are identical if they have the same sequence of fields,
  1335. and if corresponding fields have the same names, and identical types,
  1336. and identical tags.
  1337. <a href="#Exported_identifiers">Non-exported</a> field names from different
  1338. packages are always different.</li>
  1339. <li>Two pointer types are identical if they have identical base types.</li>
  1340. <li>Two function types are identical if they have the same number of parameters
  1341. and result values, corresponding parameter and result types are
  1342. identical, and either both functions are variadic or neither is.
  1343. Parameter and result names are not required to match.</li>
  1344. <li>Two interface types are identical if they have the same set of methods
  1345. with the same names and identical function types.
  1346. <a href="#Exported_identifiers">Non-exported</a> method names from different
  1347. packages are always different. The order of the methods is irrelevant.</li>
  1348. <li>Two map types are identical if they have identical key and element types.</li>
  1349. <li>Two channel types are identical if they have identical element types and
  1350. the same direction.</li>
  1351. </ul>
  1352. <p>
  1353. Given the declarations
  1354. </p>
  1355. <pre>
  1356. type (
  1357. A0 = []string
  1358. A1 = A0
  1359. A2 = struct{ a, b int }
  1360. A3 = int
  1361. A4 = func(A3, float64) *A0
  1362. A5 = func(x int, _ float64) *[]string
  1363. )
  1364. type (
  1365. B0 A0
  1366. B1 []string
  1367. B2 struct{ a, b int }
  1368. B3 struct{ a, c int }
  1369. B4 func(int, float64) *B0
  1370. B5 func(x int, y float64) *A1
  1371. )
  1372. type C0 = B0
  1373. </pre>
  1374. <p>
  1375. these types are identical:
  1376. </p>
  1377. <pre>
  1378. A0, A1, and []string
  1379. A2 and struct{ a, b int }
  1380. A3 and int
  1381. A4, func(int, float64) *[]string, and A5
  1382. B0 and C0
  1383. []int and []int
  1384. struct{ a, b *T5 } and struct{ a, b *T5 }
  1385. func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5
  1386. </pre>
  1387. <p>
  1388. <code>B0</code> and <code>B1</code> are different because they are new types
  1389. created by distinct <a href="#Type_definitions">type definitions</a>;
  1390. <code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code>
  1391. are different because <code>B0</code> is different from <code>[]string</code>.
  1392. </p>
  1393. <h3 id="Assignability">Assignability</h3>
  1394. <p>
  1395. A value <code>x</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>
  1396. ("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies:
  1397. </p>
  1398. <ul>
  1399. <li>
  1400. <code>x</code>'s type is identical to <code>T</code>.
  1401. </li>
  1402. <li>
  1403. <code>x</code>'s type <code>V</code> and <code>T</code> have identical
  1404. <a href="#Types">underlying types</a> and at least one of <code>V</code>
  1405. or <code>T</code> is not a <a href="#Type_definitions">defined</a> type.
  1406. </li>
  1407. <li>
  1408. <code>T</code> is an interface type and
  1409. <code>x</code> <a href="#Interface_types">implements</a> <code>T</code>.
  1410. </li>
  1411. <li>
  1412. <code>x</code> is a bidirectional channel value, <code>T</code> is a channel type,
  1413. <code>x</code>'s type <code>V</code> and <code>T</code> have identical element types,
  1414. and at least one of <code>V</code> or <code>T</code> is not a defined type.
  1415. </li>
  1416. <li>
  1417. <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
  1418. is a pointer, function, slice, map, channel, or interface type.
  1419. </li>
  1420. <li>
  1421. <code>x</code> is an untyped <a href="#Constants">constant</a>
  1422. <a href="#Representability">representable</a>
  1423. by a value of type <code>T</code>.
  1424. </li>
  1425. </ul>
  1426. <h3 id="Representability">Representability</h3>
  1427. <p>
  1428. A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i>
  1429. by a value of type <code>T</code> if one of the following conditions applies:
  1430. </p>
  1431. <ul>
  1432. <li>
  1433. <code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>.
  1434. </li>
  1435. <li>
  1436. <code>T</code> is a floating-point type and <code>x</code> can be rounded to <code>T</code>'s
  1437. precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE
  1438. negative zero further simplified to an unsigned zero. Note that constant values never result
  1439. in an IEEE negative zero, NaN, or infinity.
  1440. </li>
  1441. <li>
  1442. <code>T</code> is a complex type, and <code>x</code>'s
  1443. <a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code>
  1444. are representable by values of <code>T</code>'s component type (<code>float32</code> or
  1445. <code>float64</code>).
  1446. </li>
  1447. </ul>
  1448. <pre>
  1449. x T x is representable by a value of T because
  1450. 'a' byte 97 is in the set of byte values
  1451. 97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers
  1452. "foo" string "foo" is in the set of string values
  1453. 1024 int16 1024 is in the set of 16-bit integers
  1454. 42.0 byte 42 is in the set of unsigned 8-bit integers
  1455. 1e10 uint64 10000000000 is in the set of unsigned 64-bit integers
  1456. 2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values
  1457. -1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0
  1458. 0i int 0 is an integer value
  1459. (42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values
  1460. </pre>
  1461. <pre>
  1462. x T x is not representable by a value of T because
  1463. 0 bool 0 is not in the set of boolean values
  1464. 'a' string 'a' is a rune, it is not in the set of string values
  1465. 1024 byte 1024 is not in the set of unsigned 8-bit integers
  1466. -1 uint16 -1 is not in the set of unsigned 16-bit integers
  1467. 1.1 int 1.1 is not an integer value
  1468. 42i float32 (0 + 42i) is not in the set of float32 values
  1469. 1e1000 float64 1e1000 overflows to IEEE +Inf after rounding
  1470. </pre>
  1471. <h2 id="Blocks">Blocks</h2>
  1472. <p>
  1473. A <i>block</i> is a possibly empty sequence of declarations and statements
  1474. within matching brace brackets.
  1475. </p>
  1476. <pre class="ebnf">
  1477. Block = "{" StatementList "}" .
  1478. StatementList = { Statement ";" } .
  1479. </pre>
  1480. <p>
  1481. In addition to explicit blocks in the source code, there are implicit blocks:
  1482. </p>
  1483. <ol>
  1484. <li>The <i>universe block</i> encompasses all Go source text.</li>
  1485. <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
  1486. Go source text for that package.</li>
  1487. <li>Each file has a <i>file block</i> containing all Go source text
  1488. in that file.</li>
  1489. <li>Each <a href="#If_statements">"if"</a>,
  1490. <a href="#For_statements">"for"</a>, and
  1491. <a href="#Switch_statements">"switch"</a>
  1492. statement is considered to be in its own implicit block.</li>
  1493. <li>Each clause in a <a href="#Switch_statements">"switch"</a>
  1494. or <a href="#Select_statements">"select"</a> statement
  1495. acts as an implicit block.</li>
  1496. </ol>
  1497. <p>
  1498. Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
  1499. </p>
  1500. <h2 id="Declarations_and_scope">Declarations and scope</h2>
  1501. <p>
  1502. A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
  1503. <a href="#Constant_declarations">constant</a>,
  1504. <a href="#Type_declarations">type</a>,
  1505. <a href="#Variable_declarations">variable</a>,
  1506. <a href="#Function_declarations">function</a>,
  1507. <a href="#Labeled_statements">label</a>, or
  1508. <a href="#Import_declarations">package</a>.
  1509. Every identifier in a program must be declared.
  1510. No identifier may be declared twice in the same block, and
  1511. no identifier may be declared in both the file and package block.
  1512. </p>
  1513. <p>
  1514. The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
  1515. in a declaration, but it does not introduce a binding and thus is not declared.
  1516. In the package block, the identifier <code>init</code> may only be used for
  1517. <a href="#Package_initialization"><code>init</code> function</a> declarations,
  1518. and like the blank identifier it does not introduce a new binding.
  1519. </p>
  1520. <pre class="ebnf">
  1521. Declaration = ConstDecl | TypeDecl | VarDecl .
  1522. TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
  1523. </pre>
  1524. <p>
  1525. The <i>scope</i> of a declared identifier is the extent of source text in which
  1526. the identifier denotes the specified constant, type, variable, function, label, or package.
  1527. </p>
  1528. <p>
  1529. Go is lexically scoped using <a href="#Blocks">blocks</a>:
  1530. </p>
  1531. <ol>
  1532. <li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
  1533. <li>The scope of an identifier denoting a constant, type, variable,
  1534. or function (but not method) declared at top level (outside any
  1535. function) is the package block.</li>
  1536. <li>The scope of the package name of an imported package is the file block
  1537. of the file containing the import declaration.</li>
  1538. <li>The scope of an identifier denoting a method receiver, function parameter,
  1539. or result variable is the function body.</li>
  1540. <li>The scope of a constant or variable identifier declared
  1541. inside a function begins at the end of the ConstSpec or VarSpec
  1542. (ShortVarDecl for short variable declarations)
  1543. and ends at the end of the innermost containing block.</li>
  1544. <li>The scope of a type identifier declared inside a function
  1545. begins at the identifier in the TypeSpec
  1546. and ends at the end of the innermost containing block.</li>
  1547. </ol>
  1548. <p>
  1549. An identifier declared in a block may be redeclared in an inner block.
  1550. While the identifier of the inner declaration is in scope, it denotes
  1551. the entity declared by the inner declaration.
  1552. </p>
  1553. <p>
  1554. The <a href="#Package_clause">package clause</a> is not a declaration; the package name
  1555. does not appear in any scope. Its purpose is to identify the files belonging
  1556. to the same <a href="#Packages">package</a> and to specify the default package name for import
  1557. declarations.
  1558. </p>
  1559. <h3 id="Label_scopes">Label scopes</h3>
  1560. <p>
  1561. Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
  1562. used in the <a href="#Break_statements">"break"</a>,
  1563. <a href="#Continue_statements">"continue"</a>, and
  1564. <a href="#Goto_statements">"goto"</a> statements.
  1565. It is illegal to define a label that is never used.
  1566. In contrast to other identifiers, labels are not block scoped and do
  1567. not conflict with identifiers that are not labels. The scope of a label
  1568. is the body of the function in which it is declared and excludes
  1569. the body of any nested function.
  1570. </p>
  1571. <h3 id="Blank_identifier">Blank identifier</h3>
  1572. <p>
  1573. The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
  1574. It serves as an anonymous placeholder instead of a regular (non-blank)
  1575. identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
  1576. as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
  1577. </p>
  1578. <h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
  1579. <p>
  1580. The following identifiers are implicitly declared in the
  1581. <a href="#Blocks">universe block</a>:
  1582. </p>
  1583. <pre class="grammar">
  1584. Types:
  1585. bool byte complex64 complex128 error float32 float64
  1586. int int8 int16 int32 int64 rune string
  1587. uint uint8 uint16 uint32 uint64 uintptr
  1588. Constants:
  1589. true false iota
  1590. Zero value:
  1591. nil
  1592. Functions:
  1593. append cap close complex copy delete imag len
  1594. make new panic print println real recover
  1595. </pre>
  1596. <h3 id="Exported_identifiers">Exported identifiers</h3>
  1597. <p>
  1598. An identifier may be <i>exported</i> to permit access to it from another package.
  1599. An identifier is exported if both:
  1600. </p>
  1601. <ol>
  1602. <li>the first character of the identifier's name is a Unicode upper case
  1603. letter (Unicode class "Lu"); and</li>
  1604. <li>the identifier is declared in the <a href="#Blocks">package block</a>
  1605. or it is a <a href="#Struct_types">field name</a> or
  1606. <a href="#MethodName">method name</a>.</li>
  1607. </ol>
  1608. <p>
  1609. All other identifiers are not exported.
  1610. </p>
  1611. <h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
  1612. <p>
  1613. Given a set of identifiers, an identifier is called <i>unique</i> if it is
  1614. <i>different</i> from every other in the set.
  1615. Two identifiers are different if they are spelled differently, or if they
  1616. appear in different <a href="#Packages">packages</a> and are not
  1617. <a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
  1618. </p>
  1619. <h3 id="Constant_declarations">Constant declarations</h3>
  1620. <p>
  1621. A constant declaration binds a list of identifiers (the names of
  1622. the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
  1623. The number of identifiers must be equal
  1624. to the number of expressions, and the <i>n</i>th identifier on
  1625. the left is bound to the value of the <i>n</i>th expression on the
  1626. right.
  1627. </p>
  1628. <pre class="ebnf">
  1629. ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
  1630. ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
  1631. IdentifierList = identifier { "," identifier } .
  1632. ExpressionList = Expression { "," Expression } .
  1633. </pre>
  1634. <p>
  1635. If the type is present, all constants take the type specified, and
  1636. the expressions must be <a href="#Assignability">assignable</a> to that type.
  1637. If the type is omitted, the constants take the
  1638. individual types of the corresponding expressions.
  1639. If the expression values are untyped <a href="#Constants">constants</a>,
  1640. the declared constants remain untyped and the constant identifiers
  1641. denote the constant values. For instance, if the expression is a
  1642. floating-point literal, the constant identifier denotes a floating-point
  1643. constant, even if the literal's fractional part is zero.
  1644. </p>
  1645. <pre>
  1646. const Pi float64 = 3.14159265358979323846
  1647. const zero = 0.0 // untyped floating-point constant
  1648. const (
  1649. size int64 = 1024
  1650. eof = -1 // untyped integer constant
  1651. )
  1652. const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants
  1653. const u, v float32 = 0, 3 // u = 0.0, v = 3.0
  1654. </pre>
  1655. <p>
  1656. Within a parenthesized <code>const</code> declaration list the
  1657. expression list may be omitted from any but the first ConstSpec.
  1658. Such an empty list is equivalent to the textual substitution of the
  1659. first preceding non-empty expression list and its type if any.
  1660. Omitting the list of expressions is therefore equivalent to
  1661. repeating the previous list. The number of identifiers must be equal
  1662. to the number of expressions in the previous list.
  1663. Together with the <a href="#Iota"><code>iota</code> constant generator</a>
  1664. this mechanism permits light-weight declaration of sequential values:
  1665. </p>
  1666. <pre>
  1667. const (
  1668. Sunday = iota
  1669. Monday
  1670. Tuesday
  1671. Wednesday
  1672. Thursday
  1673. Friday
  1674. Partyday
  1675. numberOfDays // this constant is not exported
  1676. )
  1677. </pre>
  1678. <h3 id="Iota">Iota</h3>
  1679. <p>
  1680. Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
  1681. <code>iota</code> represents successive untyped integer <a href="#Constants">
  1682. constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a>
  1683. in that constant declaration, starting at zero.
  1684. It can be used to construct a set of related constants:
  1685. </p>
  1686. <pre>
  1687. const (
  1688. c0 = iota // c0 == 0
  1689. c1 = iota // c1 == 1
  1690. c2 = iota // c2 == 2
  1691. )
  1692. const (
  1693. a = 1 &lt;&lt; iota // a == 1 (iota == 0)
  1694. b = 1 &lt;&lt; iota // b == 2 (iota == 1)
  1695. c = 3 // c == 3 (iota == 2, unused)
  1696. d = 1 &lt;&lt; iota // d == 8 (iota == 3)
  1697. )
  1698. const (
  1699. u = iota * 42 // u == 0 (untyped integer constant)
  1700. v float64 = iota * 42 // v == 42.0 (float64 constant)
  1701. w = iota * 42 // w == 84 (untyped integer constant)
  1702. )
  1703. const x = iota // x == 0
  1704. const y = iota // y == 0
  1705. </pre>
  1706. <p>
  1707. By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value:
  1708. </p>
  1709. <pre>
  1710. const (
  1711. bit0, mask0 = 1 &lt;&lt; iota, 1&lt;&lt;iota - 1 // bit0 == 1, mask0 == 0 (iota == 0)
  1712. bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1)
  1713. _, _ // (iota == 2, unused)
  1714. bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3)
  1715. )
  1716. </pre>
  1717. <p>
  1718. This last example exploits the <a href="#Constant_declarations">implicit repetition</a>
  1719. of the last non-empty expression list.
  1720. </p>
  1721. <h3 id="Type_declarations">Type declarations</h3>
  1722. <p>
  1723. A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>.
  1724. Type declarations come in two forms: alias declarations and type definitions.
  1725. </p>
  1726. <pre class="ebnf">
  1727. TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
  1728. TypeSpec = AliasDecl | TypeDef .
  1729. </pre>
  1730. <h4 id="Alias_declarations">Alias declarations</h4>
  1731. <p>
  1732. An alias declaration binds an identifier to the given type.
  1733. </p>
  1734. <pre class="ebnf">
  1735. AliasDecl = identifier "=" Type .
  1736. </pre>
  1737. <p>
  1738. Within the <a href="#Declarations_and_scope">scope</a> of
  1739. the identifier, it serves as an <i>alias</i> for the type.
  1740. </p>
  1741. <pre>
  1742. type (
  1743. nodeList = []*Node // nodeList and []*Node are identical types
  1744. Polar = polar // Polar and polar denote identical types
  1745. )
  1746. </pre>
  1747. <h4 id="Type_definitions">Type definitions</h4>
  1748. <p>
  1749. A type definition creates a new, distinct type with the same
  1750. <a href="#Types">underlying type</a> and operations as the given type,
  1751. and binds an identifier to it.
  1752. </p>
  1753. <pre class="ebnf">
  1754. TypeDef = identifier Type .
  1755. </pre>
  1756. <p>
  1757. The new type is called a <i>defined type</i>.
  1758. It is <a href="#Type_identity">different</a> from any other type,
  1759. including the type it is created from.
  1760. </p>
  1761. <pre>
  1762. type (
  1763. Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types
  1764. polar Point // polar and Point denote different types
  1765. )
  1766. type TreeNode struct {
  1767. left, right *TreeNode
  1768. value *Comparable
  1769. }
  1770. type Block interface {
  1771. BlockSize() int
  1772. Encrypt(src, dst []byte)
  1773. Decrypt(src, dst []byte)
  1774. }
  1775. </pre>
  1776. <p>
  1777. A defined type may have <a href="#Method_declarations">methods</a> associated with it.
  1778. It does not inherit any methods bound to the given type,
  1779. but the <a href="#Method_sets">method set</a>
  1780. of an interface type or of elements of a composite type remains unchanged:
  1781. </p>
  1782. <pre>
  1783. // A Mutex is a data type with two methods, Lock and Unlock.
  1784. type Mutex struct { /* Mutex fields */ }
  1785. func (m *Mutex) Lock() { /* Lock implementation */ }
  1786. func (m *Mutex) Unlock() { /* Unlock implementation */ }
  1787. // NewMutex has the same composition as Mutex but its method set is empty.
  1788. type NewMutex Mutex
  1789. // The method set of PtrMutex's underlying type *Mutex remains unchanged,
  1790. // but the method set of PtrMutex is empty.
  1791. type PtrMutex *Mutex
  1792. // The method set of *PrintableMutex contains the methods
  1793. // Lock and Unlock bound to its embedded field Mutex.
  1794. type PrintableMutex struct {
  1795. Mutex
  1796. }
  1797. // MyBlock is an interface type that has the same method set as Block.
  1798. type MyBlock Block
  1799. </pre>
  1800. <p>
  1801. Type definitions may be used to define different boolean, numeric,
  1802. or string types and associate methods with them:
  1803. </p>
  1804. <pre>
  1805. type TimeZone int
  1806. const (
  1807. EST TimeZone = -(5 + iota)
  1808. CST
  1809. MST
  1810. PST
  1811. )
  1812. func (tz TimeZone) String() string {
  1813. return fmt.Sprintf("GMT%+dh", tz)
  1814. }
  1815. </pre>
  1816. <h3 id="Variable_declarations">Variable declarations</h3>
  1817. <p>
  1818. A variable declaration creates one or more <a href="#Variables">variables</a>,
  1819. binds corresponding identifiers to them, and gives each a type and an initial value.
  1820. </p>
  1821. <pre class="ebnf">
  1822. VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
  1823. VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
  1824. </pre>
  1825. <pre>
  1826. var i int
  1827. var U, V, W float64
  1828. var k = 0
  1829. var x, y float32 = -1, -2
  1830. var (
  1831. i int
  1832. u, v, s = 2.0, 3.0, "bar"
  1833. )
  1834. var re, im = complexSqrt(-1)
  1835. var _, found = entries[name] // map lookup; only interested in "found"
  1836. </pre>
  1837. <p>
  1838. If a list of expressions is given, the variables are initialized
  1839. with the expressions following the rules for <a href="#Assignments">assignments</a>.
  1840. Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
  1841. </p>
  1842. <p>
  1843. If a type is present, each variable is given that type.
  1844. Otherwise, each variable is given the type of the corresponding
  1845. initialization value in the assignment.
  1846. If that value is an untyped constant, it is first implicitly
  1847. <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
  1848. if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
  1849. The predeclared value <code>nil</code> cannot be used to initialize a variable
  1850. with no explicit type.
  1851. </p>
  1852. <pre>
  1853. var d = math.Sin(0.5) // d is float64
  1854. var i = 42 // i is int
  1855. var t, ok = x.(T) // t is T, ok is bool
  1856. var n = nil // illegal
  1857. </pre>
  1858. <p>
  1859. Implementation restriction: A compiler may make it illegal to declare a variable
  1860. inside a <a href="#Function_declarations">function body</a> if the variable is
  1861. never used.
  1862. </p>
  1863. <h3 id="Short_variable_declarations">Short variable declarations</h3>
  1864. <p>
  1865. A <i>short variable declaration</i> uses the syntax:
  1866. </p>
  1867. <pre class="ebnf">
  1868. ShortVarDecl = IdentifierList ":=" ExpressionList .
  1869. </pre>
  1870. <p>
  1871. It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
  1872. with initializer expressions but no types:
  1873. </p>
  1874. <pre class="grammar">
  1875. "var" IdentifierList = ExpressionList .
  1876. </pre>
  1877. <pre>
  1878. i, j := 0, 10
  1879. f := func() int { return 7 }
  1880. ch := make(chan int)
  1881. r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any
  1882. _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
  1883. </pre>
  1884. <p>
  1885. Unlike regular variable declarations, a short variable declaration may <i>redeclare</i>
  1886. variables provided they were originally declared earlier in the same block
  1887. (or the parameter lists if the block is the function body) with the same type,
  1888. and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new.
  1889. As a consequence, redeclaration can only appear in a multi-variable short declaration.
  1890. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
  1891. </p>
  1892. <pre>
  1893. field1, offset := nextField(str, 0)
  1894. field2, offset := nextField(str, offset) // redeclares offset
  1895. a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere
  1896. </pre>
  1897. <p>
  1898. Short variable declarations may appear only inside functions.
  1899. In some contexts such as the initializers for
  1900. <a href="#If_statements">"if"</a>,
  1901. <a href="#For_statements">"for"</a>, or
  1902. <a href="#Switch_statements">"switch"</a> statements,
  1903. they can be used to declare local temporary variables.
  1904. </p>
  1905. <h3 id="Function_declarations">Function declarations</h3>
  1906. <p>
  1907. A function declaration binds an identifier, the <i>function name</i>,
  1908. to a function.
  1909. </p>
  1910. <pre class="ebnf">
  1911. FunctionDecl = "func" FunctionName Signature [ FunctionBody ] .
  1912. FunctionName = identifier .
  1913. FunctionBody = Block .
  1914. </pre>
  1915. <p>
  1916. If the function's <a href="#Function_types">signature</a> declares
  1917. result parameters, the function body's statement list must end in
  1918. a <a href="#Terminating_statements">terminating statement</a>.
  1919. </p>
  1920. <pre>
  1921. func IndexRune(s string, r rune) int {
  1922. for i, c := range s {
  1923. if c == r {
  1924. return i
  1925. }
  1926. }
  1927. // invalid: missing return statement
  1928. }
  1929. </pre>
  1930. <p>
  1931. A function declaration may omit the body. Such a declaration provides the
  1932. signature for a function implemented outside Go, such as an assembly routine.
  1933. </p>
  1934. <pre>
  1935. func min(x int, y int) int {
  1936. if x &lt; y {
  1937. return x
  1938. }
  1939. return y
  1940. }
  1941. func flushICache(begin, end uintptr) // implemented externally
  1942. </pre>
  1943. <h3 id="Method_declarations">Method declarations</h3>
  1944. <p>
  1945. A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
  1946. A method declaration binds an identifier, the <i>method name</i>, to a method,
  1947. and associates the method with the receiver's <i>base type</i>.
  1948. </p>
  1949. <pre class="ebnf">
  1950. MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] .
  1951. Receiver = Parameters .
  1952. </pre>
  1953. <p>
  1954. The receiver is specified via an extra parameter section preceding the method
  1955. name. That parameter section must declare a single non-variadic parameter, the receiver.
  1956. Its type must be a <a href="#Type_definitions">defined</a> type <code>T</code> or a
  1957. pointer to a defined type <code>T</code>. <code>T</code> is called the receiver
  1958. <i>base type</i>. A receiver base type cannot be a pointer or interface type and
  1959. it must be defined in the same package as the method.
  1960. The method is said to be <i>bound</i> to its receiver base type and the method name
  1961. is visible only within <a href="#Selectors">selectors</a> for type <code>T</code>
  1962. or <code>*T</code>.
  1963. </p>
  1964. <p>
  1965. A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
  1966. <a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
  1967. If the receiver's value is not referenced inside the body of the method,
  1968. its identifier may be omitted in the declaration. The same applies in
  1969. general to parameters of functions and methods.
  1970. </p>
  1971. <p>
  1972. For a base type, the non-blank names of methods bound to it must be unique.
  1973. If the base type is a <a href="#Struct_types">struct type</a>,
  1974. the non-blank method and field names must be distinct.
  1975. </p>
  1976. <p>
  1977. Given defined type <code>Point</code>, the declarations
  1978. </p>
  1979. <pre>
  1980. func (p *Point) Length() float64 {
  1981. return math.Sqrt(p.x * p.x + p.y * p.y)
  1982. }
  1983. func (p *Point) Scale(factor float64) {
  1984. p.x *= factor
  1985. p.y *= factor
  1986. }
  1987. </pre>
  1988. <p>
  1989. bind the methods <code>Length</code> and <code>Scale</code>,
  1990. with receiver type <code>*Point</code>,
  1991. to the base type <code>Point</code>.
  1992. </p>
  1993. <p>
  1994. The type of a method is the type of a function with the receiver as first
  1995. argument. For instance, the method <code>Scale</code> has type
  1996. </p>
  1997. <pre>
  1998. func(p *Point, factor float64)
  1999. </pre>
  2000. <p>
  2001. However, a function declared this way is not a method.
  2002. </p>
  2003. <h2 id="Expressions">Expressions</h2>
  2004. <p>
  2005. An expression specifies the computation of a value by applying
  2006. operators and functions to operands.
  2007. </p>
  2008. <h3 id="Operands">Operands</h3>
  2009. <p>
  2010. Operands denote the elementary values in an expression. An operand may be a
  2011. literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
  2012. non-<a href="#Blank_identifier">blank</a> identifier denoting a
  2013. <a href="#Constant_declarations">constant</a>,
  2014. <a href="#Variable_declarations">variable</a>, or
  2015. <a href="#Function_declarations">function</a>,
  2016. or a parenthesized expression.
  2017. </p>
  2018. <p>
  2019. The <a href="#Blank_identifier">blank identifier</a> may appear as an
  2020. operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
  2021. </p>
  2022. <pre class="ebnf">
  2023. Operand = Literal | OperandName | "(" Expression ")" .
  2024. Literal = BasicLit | CompositeLit | FunctionLit .
  2025. BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
  2026. OperandName = identifier | QualifiedIdent .
  2027. </pre>
  2028. <h3 id="Qualified_identifiers">Qualified identifiers</h3>
  2029. <p>
  2030. A qualified identifier is an identifier qualified with a package name prefix.
  2031. Both the package name and the identifier must not be
  2032. <a href="#Blank_identifier">blank</a>.
  2033. </p>
  2034. <pre class="ebnf">
  2035. QualifiedIdent = PackageName "." identifier .
  2036. </pre>
  2037. <p>
  2038. A qualified identifier accesses an identifier in a different package, which
  2039. must be <a href="#Import_declarations">imported</a>.
  2040. The identifier must be <a href="#Exported_identifiers">exported</a> and
  2041. declared in the <a href="#Blocks">package block</a> of that package.
  2042. </p>
  2043. <pre>
  2044. math.Sin // denotes the Sin function in package math
  2045. </pre>
  2046. <h3 id="Composite_literals">Composite literals</h3>
  2047. <p>
  2048. Composite literals construct values for structs, arrays, slices, and maps
  2049. and create a new value each time they are evaluated.
  2050. They consist of the type of the literal followed by a brace-bound list of elements.
  2051. Each element may optionally be preceded by a corresponding key.
  2052. </p>
  2053. <pre class="ebnf">
  2054. CompositeLit = LiteralType LiteralValue .
  2055. LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
  2056. SliceType | MapType | TypeName .
  2057. LiteralValue = "{" [ ElementList [ "," ] ] "}" .
  2058. ElementList = KeyedElement { "," KeyedElement } .
  2059. KeyedElement = [ Key ":" ] Element .
  2060. Key = FieldName | Expression | LiteralValue .
  2061. FieldName = identifier .
  2062. Element = Expression | LiteralValue .
  2063. </pre>
  2064. <p>
  2065. The LiteralType's underlying type must be a struct, array, slice, or map type
  2066. (the grammar enforces this constraint except when the type is given
  2067. as a TypeName).
  2068. The types of the elements and keys must be <a href="#Assignability">assignable</a>
  2069. to the respective field, element, and key types of the literal type;
  2070. there is no additional conversion.
  2071. The key is interpreted as a field name for struct literals,
  2072. an index for array and slice literals, and a key for map literals.
  2073. For map literals, all elements must have a key. It is an error
  2074. to specify multiple elements with the same field name or
  2075. constant key value. For non-constant map keys, see the section on
  2076. <a href="#Order_of_evaluation">evaluation order</a>.
  2077. </p>
  2078. <p>
  2079. For struct literals the following rules apply:
  2080. </p>
  2081. <ul>
  2082. <li>A key must be a field name declared in the struct type.
  2083. </li>
  2084. <li>An element list that does not contain any keys must
  2085. list an element for each struct field in the
  2086. order in which the fields are declared.
  2087. </li>
  2088. <li>If any element has a key, every element must have a key.
  2089. </li>
  2090. <li>An element list that contains keys does not need to
  2091. have an element for each struct field. Omitted fields
  2092. get the zero value for that field.
  2093. </li>
  2094. <li>A literal may omit the element list; such a literal evaluates
  2095. to the zero value for its type.
  2096. </li>
  2097. <li>It is an error to specify an element for a non-exported
  2098. field of a struct belonging to a different package.
  2099. </li>
  2100. </ul>
  2101. <p>
  2102. Given the declarations
  2103. </p>
  2104. <pre>
  2105. type Point3D struct { x, y, z float64 }
  2106. type Line struct { p, q Point3D }
  2107. </pre>
  2108. <p>
  2109. one may write
  2110. </p>
  2111. <pre>
  2112. origin := Point3D{} // zero value for Point3D
  2113. line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x
  2114. </pre>
  2115. <p>
  2116. For array and slice literals the following rules apply:
  2117. </p>
  2118. <ul>
  2119. <li>Each element has an associated integer index marking
  2120. its position in the array.
  2121. </li>
  2122. <li>An element with a key uses the key as its index. The
  2123. key must be a non-negative constant
  2124. <a href="#Representability">representable</a> by
  2125. a value of type <code>int</code>; and if it is typed
  2126. it must be of integer type.
  2127. </li>
  2128. <li>An element without a key uses the previous element's index plus one.
  2129. If the first element has no key, its index is zero.
  2130. </li>
  2131. </ul>
  2132. <p>
  2133. <a href="#Address_operators">Taking the address</a> of a composite literal
  2134. generates a pointer to a unique <a href="#Variables">variable</a> initialized
  2135. with the literal's value.
  2136. </p>
  2137. <pre>
  2138. var pointer *Point3D = &amp;Point3D{y: 1000}
  2139. </pre>
  2140. <p>
  2141. Note that the <a href="#The_zero_value">zero value</a> for a slice or map
  2142. type is not the same as an initialized but empty value of the same type.
  2143. Consequently, taking the address of an empty slice or map composite literal
  2144. does not have the same effect as allocating a new slice or map value with
  2145. <a href="#Allocation">new</a>.
  2146. </p>
  2147. <pre>
  2148. p1 := &amp;[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0
  2149. p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
  2150. </pre>
  2151. <p>
  2152. The length of an array literal is the length specified in the literal type.
  2153. If fewer elements than the length are provided in the literal, the missing
  2154. elements are set to the zero value for the array element type.
  2155. It is an error to provide elements with index values outside the index range
  2156. of the array. The notation <code>...</code> specifies an array length equal
  2157. to the maximum element index plus one.
  2158. </p>
  2159. <pre>
  2160. buffer := [10]string{} // len(buffer) == 10
  2161. intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6
  2162. days := [...]string{"Sat", "Sun"} // len(days) == 2
  2163. </pre>
  2164. <p>
  2165. A slice literal describes the entire underlying array literal.
  2166. Thus the length and capacity of a slice literal are the maximum
  2167. element index plus one. A slice literal has the form
  2168. </p>
  2169. <pre>
  2170. []T{x1, x2, … xn}
  2171. </pre>
  2172. <p>
  2173. and is shorthand for a slice operation applied to an array:
  2174. </p>
  2175. <pre>
  2176. tmp := [n]T{x1, x2, … xn}
  2177. tmp[0 : n]
  2178. </pre>
  2179. <p>
  2180. Within a composite literal of array, slice, or map type <code>T</code>,
  2181. elements or map keys that are themselves composite literals may elide the respective
  2182. literal type if it is identical to the element or key type of <code>T</code>.
  2183. Similarly, elements or keys that are addresses of composite literals may elide
  2184. the <code>&amp;T</code> when the element or key type is <code>*T</code>.
  2185. </p>
  2186. <pre>
  2187. [...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
  2188. [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}
  2189. [][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}
  2190. map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}}
  2191. map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"}
  2192. type PPoint *Point
  2193. [2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&amp;Point{1.5, -3.5}, &amp;Point{}}
  2194. [2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&amp;Point{1.5, -3.5}), PPoint(&amp;Point{})}
  2195. </pre>
  2196. <p>
  2197. A parsing ambiguity arises when a composite literal using the
  2198. TypeName form of the LiteralType appears as an operand between the
  2199. <a href="#Keywords">keyword</a> and the opening brace of the block
  2200. of an "if", "for", or "switch" statement, and the composite literal
  2201. is not enclosed in parentheses, square brackets, or curly braces.
  2202. In this rare case, the opening brace of the literal is erroneously parsed
  2203. as the one introducing the block of statements. To resolve the ambiguity,
  2204. the composite literal must appear within parentheses.
  2205. </p>
  2206. <pre>
  2207. if x == (T{a,b,c}[i]) { … }
  2208. if (x == T{a,b,c}[i]) { … }
  2209. </pre>
  2210. <p>
  2211. Examples of valid array, slice, and map literals:
  2212. </p>
  2213. <pre>
  2214. // list of prime numbers
  2215. primes := []int{2, 3, 5, 7, 9, 2147483647}
  2216. // vowels[ch] is true if ch is a vowel
  2217. vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
  2218. // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
  2219. filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
  2220. // frequencies in Hz for equal-tempered scale (A4 = 440Hz)
  2221. noteFrequency := map[string]float32{
  2222. "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
  2223. "G0": 24.50, "A0": 27.50, "B0": 30.87,
  2224. }
  2225. </pre>
  2226. <h3 id="Function_literals">Function literals</h3>
  2227. <p>
  2228. A function literal represents an anonymous <a href="#Function_declarations">function</a>.
  2229. </p>
  2230. <pre class="ebnf">
  2231. FunctionLit = "func" Signature FunctionBody .
  2232. </pre>
  2233. <pre>
  2234. func(a, b int, z float64) bool { return a*b &lt; int(z) }
  2235. </pre>
  2236. <p>
  2237. A function literal can be assigned to a variable or invoked directly.
  2238. </p>
  2239. <pre>
  2240. f := func(x, y int) int { return x + y }
  2241. func(ch chan int) { ch &lt;- ACK }(replyChan)
  2242. </pre>
  2243. <p>
  2244. Function literals are <i>closures</i>: they may refer to variables
  2245. defined in a surrounding function. Those variables are then shared between
  2246. the surrounding function and the function literal, and they survive as long
  2247. as they are accessible.
  2248. </p>
  2249. <h3 id="Primary_expressions">Primary expressions</h3>
  2250. <p>
  2251. Primary expressions are the operands for unary and binary expressions.
  2252. </p>
  2253. <pre class="ebnf">
  2254. PrimaryExpr =
  2255. Operand |
  2256. Conversion |
  2257. MethodExpr |
  2258. PrimaryExpr Selector |
  2259. PrimaryExpr Index |
  2260. PrimaryExpr Slice |
  2261. PrimaryExpr TypeAssertion |
  2262. PrimaryExpr Arguments .
  2263. Selector = "." identifier .
  2264. Index = "[" Expression "]" .
  2265. Slice = "[" [ Expression ] ":" [ Expression ] "]" |
  2266. "[" [ Expression ] ":" Expression ":" Expression "]" .
  2267. TypeAssertion = "." "(" Type ")" .
  2268. Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
  2269. </pre>
  2270. <pre>
  2271. x
  2272. 2
  2273. (s + ".txt")
  2274. f(3.1415, true)
  2275. Point{1, 2}
  2276. m["foo"]
  2277. s[i : j + 1]
  2278. obj.color
  2279. f.p[i].x()
  2280. </pre>
  2281. <h3 id="Selectors">Selectors</h3>
  2282. <p>
  2283. For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
  2284. that is not a <a href="#Package_clause">package name</a>, the
  2285. <i>selector expression</i>
  2286. </p>
  2287. <pre>
  2288. x.f
  2289. </pre>
  2290. <p>
  2291. denotes the field or method <code>f</code> of the value <code>x</code>
  2292. (or sometimes <code>*x</code>; see below).
  2293. The identifier <code>f</code> is called the (field or method) <i>selector</i>;
  2294. it must not be the <a href="#Blank_identifier">blank identifier</a>.
  2295. The type of the selector expression is the type of <code>f</code>.
  2296. If <code>x</code> is a package name, see the section on
  2297. <a href="#Qualified_identifiers">qualified identifiers</a>.
  2298. </p>
  2299. <p>
  2300. A selector <code>f</code> may denote a field or method <code>f</code> of
  2301. a type <code>T</code>, or it may refer
  2302. to a field or method <code>f</code> of a nested
  2303. <a href="#Struct_types">embedded field</a> of <code>T</code>.
  2304. The number of embedded fields traversed
  2305. to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
  2306. The depth of a field or method <code>f</code>
  2307. declared in <code>T</code> is zero.
  2308. The depth of a field or method <code>f</code> declared in
  2309. an embedded field <code>A</code> in <code>T</code> is the
  2310. depth of <code>f</code> in <code>A</code> plus one.
  2311. </p>
  2312. <p>
  2313. The following rules apply to selectors:
  2314. </p>
  2315. <ol>
  2316. <li>
  2317. For a value <code>x</code> of type <code>T</code> or <code>*T</code>
  2318. where <code>T</code> is not a pointer or interface type,
  2319. <code>x.f</code> denotes the field or method at the shallowest depth
  2320. in <code>T</code> where there
  2321. is such an <code>f</code>.
  2322. If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
  2323. with shallowest depth, the selector expression is illegal.
  2324. </li>
  2325. <li>
  2326. For a value <code>x</code> of type <code>I</code> where <code>I</code>
  2327. is an interface type, <code>x.f</code> denotes the actual method with name
  2328. <code>f</code> of the dynamic value of <code>x</code>.
  2329. If there is no method with name <code>f</code> in the
  2330. <a href="#Method_sets">method set</a> of <code>I</code>, the selector
  2331. expression is illegal.
  2332. </li>
  2333. <li>
  2334. As an exception, if the type of <code>x</code> is a <a href="#Type_definitions">defined</a>
  2335. pointer type and <code>(*x).f</code> is a valid selector expression denoting a field
  2336. (but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>.
  2337. </li>
  2338. <li>
  2339. In all other cases, <code>x.f</code> is illegal.
  2340. </li>
  2341. <li>
  2342. If <code>x</code> is of pointer type and has the value
  2343. <code>nil</code> and <code>x.f</code> denotes a struct field,
  2344. assigning to or evaluating <code>x.f</code>
  2345. causes a <a href="#Run_time_panics">run-time panic</a>.
  2346. </li>
  2347. <li>
  2348. If <code>x</code> is of interface type and has the value
  2349. <code>nil</code>, <a href="#Calls">calling</a> or
  2350. <a href="#Method_values">evaluating</a> the method <code>x.f</code>
  2351. causes a <a href="#Run_time_panics">run-time panic</a>.
  2352. </li>
  2353. </ol>
  2354. <p>
  2355. For example, given the declarations:
  2356. </p>
  2357. <pre>
  2358. type T0 struct {
  2359. x int
  2360. }
  2361. func (*T0) M0()
  2362. type T1 struct {
  2363. y int
  2364. }
  2365. func (T1) M1()
  2366. type T2 struct {
  2367. z int
  2368. T1
  2369. *T0
  2370. }
  2371. func (*T2) M2()
  2372. type Q *T2
  2373. var t T2 // with t.T0 != nil
  2374. var p *T2 // with p != nil and (*p).T0 != nil
  2375. var q Q = p
  2376. </pre>
  2377. <p>
  2378. one may write:
  2379. </p>
  2380. <pre>
  2381. t.z // t.z
  2382. t.y // t.T1.y
  2383. t.x // (*t.T0).x
  2384. p.z // (*p).z
  2385. p.y // (*p).T1.y
  2386. p.x // (*(*p).T0).x
  2387. q.x // (*(*q).T0).x (*q).x is a valid field selector
  2388. p.M0() // ((*p).T0).M0() M0 expects *T0 receiver
  2389. p.M1() // ((*p).T1).M1() M1 expects T1 receiver
  2390. p.M2() // p.M2() M2 expects *T2 receiver
  2391. t.M2() // (&amp;t).M2() M2 expects *T2 receiver, see section on Calls
  2392. </pre>
  2393. <p>
  2394. but the following is invalid:
  2395. </p>
  2396. <pre>
  2397. q.M0() // (*q).M0 is valid but not a field selector
  2398. </pre>
  2399. <h3 id="Method_expressions">Method expressions</h3>
  2400. <p>
  2401. If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
  2402. <code>T.M</code> is a function that is callable as a regular function
  2403. with the same arguments as <code>M</code> prefixed by an additional
  2404. argument that is the receiver of the method.
  2405. </p>
  2406. <pre class="ebnf">
  2407. MethodExpr = ReceiverType "." MethodName .
  2408. ReceiverType = Type .
  2409. </pre>
  2410. <p>
  2411. Consider a struct type <code>T</code> with two methods,
  2412. <code>Mv</code>, whose receiver is of type <code>T</code>, and
  2413. <code>Mp</code>, whose receiver is of type <code>*T</code>.
  2414. </p>
  2415. <pre>
  2416. type T struct {
  2417. a int
  2418. }
  2419. func (tv T) Mv(a int) int { return 0 } // value receiver
  2420. func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
  2421. var t T
  2422. </pre>
  2423. <p>
  2424. The expression
  2425. </p>
  2426. <pre>
  2427. T.Mv
  2428. </pre>
  2429. <p>
  2430. yields a function equivalent to <code>Mv</code> but
  2431. with an explicit receiver as its first argument; it has signature
  2432. </p>
  2433. <pre>
  2434. func(tv T, a int) int
  2435. </pre>
  2436. <p>
  2437. That function may be called normally with an explicit receiver, so
  2438. these five invocations are equivalent:
  2439. </p>
  2440. <pre>
  2441. t.Mv(7)
  2442. T.Mv(t, 7)
  2443. (T).Mv(t, 7)
  2444. f1 := T.Mv; f1(t, 7)
  2445. f2 := (T).Mv; f2(t, 7)
  2446. </pre>
  2447. <p>
  2448. Similarly, the expression
  2449. </p>
  2450. <pre>
  2451. (*T).Mp
  2452. </pre>
  2453. <p>
  2454. yields a function value representing <code>Mp</code> with signature
  2455. </p>
  2456. <pre>
  2457. func(tp *T, f float32) float32
  2458. </pre>
  2459. <p>
  2460. For a method with a value receiver, one can derive a function
  2461. with an explicit pointer receiver, so
  2462. </p>
  2463. <pre>
  2464. (*T).Mv
  2465. </pre>
  2466. <p>
  2467. yields a function value representing <code>Mv</code> with signature
  2468. </p>
  2469. <pre>
  2470. func(tv *T, a int) int
  2471. </pre>
  2472. <p>
  2473. Such a function indirects through the receiver to create a value
  2474. to pass as the receiver to the underlying method;
  2475. the method does not overwrite the value whose address is passed in
  2476. the function call.
  2477. </p>
  2478. <p>
  2479. The final case, a value-receiver function for a pointer-receiver method,
  2480. is illegal because pointer-receiver methods are not in the method set
  2481. of the value type.
  2482. </p>
  2483. <p>
  2484. Function values derived from methods are called with function call syntax;
  2485. the receiver is provided as the first argument to the call.
  2486. That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
  2487. as <code>f(t, 7)</code> not <code>t.f(7)</code>.
  2488. To construct a function that binds the receiver, use a
  2489. <a href="#Function_literals">function literal</a> or
  2490. <a href="#Method_values">method value</a>.
  2491. </p>
  2492. <p>
  2493. It is legal to derive a function value from a method of an interface type.
  2494. The resulting function takes an explicit receiver of that interface type.
  2495. </p>
  2496. <h3 id="Method_values">Method values</h3>
  2497. <p>
  2498. If the expression <code>x</code> has static type <code>T</code> and
  2499. <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
  2500. <code>x.M</code> is called a <i>method value</i>.
  2501. The method value <code>x.M</code> is a function value that is callable
  2502. with the same arguments as a method call of <code>x.M</code>.
  2503. The expression <code>x</code> is evaluated and saved during the evaluation of the
  2504. method value; the saved copy is then used as the receiver in any calls,
  2505. which may be executed later.
  2506. </p>
  2507. <pre>
  2508. type S struct { *T }
  2509. type T int
  2510. func (t T) M() { print(t) }
  2511. t := new(T)
  2512. s := S{T: t}
  2513. f := t.M // receiver *t is evaluated and stored in f
  2514. g := s.M // receiver *(s.T) is evaluated and stored in g
  2515. *t = 42 // does not affect stored receivers in f and g
  2516. </pre>
  2517. <p>
  2518. The type <code>T</code> may be an interface or non-interface type.
  2519. </p>
  2520. <p>
  2521. As in the discussion of <a href="#Method_expressions">method expressions</a> above,
  2522. consider a struct type <code>T</code> with two methods,
  2523. <code>Mv</code>, whose receiver is of type <code>T</code>, and
  2524. <code>Mp</code>, whose receiver is of type <code>*T</code>.
  2525. </p>
  2526. <pre>
  2527. type T struct {
  2528. a int
  2529. }
  2530. func (tv T) Mv(a int) int { return 0 } // value receiver
  2531. func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
  2532. var t T
  2533. var pt *T
  2534. func makeT() T
  2535. </pre>
  2536. <p>
  2537. The expression
  2538. </p>
  2539. <pre>
  2540. t.Mv
  2541. </pre>
  2542. <p>
  2543. yields a function value of type
  2544. </p>
  2545. <pre>
  2546. func(int) int
  2547. </pre>
  2548. <p>
  2549. These two invocations are equivalent:
  2550. </p>
  2551. <pre>
  2552. t.Mv(7)
  2553. f := t.Mv; f(7)
  2554. </pre>
  2555. <p>
  2556. Similarly, the expression
  2557. </p>
  2558. <pre>
  2559. pt.Mp
  2560. </pre>
  2561. <p>
  2562. yields a function value of type
  2563. </p>
  2564. <pre>
  2565. func(float32) float32
  2566. </pre>
  2567. <p>
  2568. As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
  2569. using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
  2570. </p>
  2571. <p>
  2572. As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
  2573. using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&amp;t).Mp</code>.
  2574. </p>
  2575. <pre>
  2576. f := t.Mv; f(7) // like t.Mv(7)
  2577. f := pt.Mp; f(7) // like pt.Mp(7)
  2578. f := pt.Mv; f(7) // like (*pt).Mv(7)
  2579. f := t.Mp; f(7) // like (&amp;t).Mp(7)
  2580. f := makeT().Mp // invalid: result of makeT() is not addressable
  2581. </pre>
  2582. <p>
  2583. Although the examples above use non-interface types, it is also legal to create a method value
  2584. from a value of interface type.
  2585. </p>
  2586. <pre>
  2587. var i interface { M(int) } = myVal
  2588. f := i.M; f(7) // like i.M(7)
  2589. </pre>
  2590. <h3 id="Index_expressions">Index expressions</h3>
  2591. <p>
  2592. A primary expression of the form
  2593. </p>
  2594. <pre>
  2595. a[x]
  2596. </pre>
  2597. <p>
  2598. denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
  2599. The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
  2600. The following rules apply:
  2601. </p>
  2602. <p>
  2603. If <code>a</code> is not a map:
  2604. </p>
  2605. <ul>
  2606. <li>the index <code>x</code> must be of integer type or an untyped constant</li>
  2607. <li>a constant index must be non-negative and
  2608. <a href="#Representability">representable</a> by a value of type <code>int</code></li>
  2609. <li>a constant index that is untyped is given type <code>int</code></li>
  2610. <li>the index <code>x</code> is <i>in range</i> if <code>0 &lt;= x &lt; len(a)</code>,
  2611. otherwise it is <i>out of range</i></li>
  2612. </ul>
  2613. <p>
  2614. For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
  2615. </p>
  2616. <ul>
  2617. <li>a <a href="#Constants">constant</a> index must be in range</li>
  2618. <li>if <code>x</code> is out of range at run time,
  2619. a <a href="#Run_time_panics">run-time panic</a> occurs</li>
  2620. <li><code>a[x]</code> is the array element at index <code>x</code> and the type of
  2621. <code>a[x]</code> is the element type of <code>A</code></li>
  2622. </ul>
  2623. <p>
  2624. For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
  2625. </p>
  2626. <ul>
  2627. <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
  2628. </ul>
  2629. <p>
  2630. For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
  2631. </p>
  2632. <ul>
  2633. <li>if <code>x</code> is out of range at run time,
  2634. a <a href="#Run_time_panics">run-time panic</a> occurs</li>
  2635. <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
  2636. <code>a[x]</code> is the element type of <code>S</code></li>
  2637. </ul>
  2638. <p>
  2639. For <code>a</code> of <a href="#String_types">string type</a>:
  2640. </p>
  2641. <ul>
  2642. <li>a <a href="#Constants">constant</a> index must be in range
  2643. if the string <code>a</code> is also constant</li>
  2644. <li>if <code>x</code> is out of range at run time,
  2645. a <a href="#Run_time_panics">run-time panic</a> occurs</li>
  2646. <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
  2647. <code>a[x]</code> is <code>byte</code></li>
  2648. <li><code>a[x]</code> may not be assigned to</li>
  2649. </ul>
  2650. <p>
  2651. For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
  2652. </p>
  2653. <ul>
  2654. <li><code>x</code>'s type must be
  2655. <a href="#Assignability">assignable</a>
  2656. to the key type of <code>M</code></li>
  2657. <li>if the map contains an entry with key <code>x</code>,
  2658. <code>a[x]</code> is the map element with key <code>x</code>
  2659. and the type of <code>a[x]</code> is the element type of <code>M</code></li>
  2660. <li>if the map is <code>nil</code> or does not contain such an entry,
  2661. <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
  2662. for the element type of <code>M</code></li>
  2663. </ul>
  2664. <p>
  2665. Otherwise <code>a[x]</code> is illegal.
  2666. </p>
  2667. <p>
  2668. An index expression on a map <code>a</code> of type <code>map[K]V</code>
  2669. used in an <a href="#Assignments">assignment</a> or initialization of the special form
  2670. </p>
  2671. <pre>
  2672. v, ok = a[x]
  2673. v, ok := a[x]
  2674. var v, ok = a[x]
  2675. </pre>
  2676. <p>
  2677. yields an additional untyped boolean value. The value of <code>ok</code> is
  2678. <code>true</code> if the key <code>x</code> is present in the map, and
  2679. <code>false</code> otherwise.
  2680. </p>
  2681. <p>
  2682. Assigning to an element of a <code>nil</code> map causes a
  2683. <a href="#Run_time_panics">run-time panic</a>.
  2684. </p>
  2685. <h3 id="Slice_expressions">Slice expressions</h3>
  2686. <p>
  2687. Slice expressions construct a substring or slice from a string, array, pointer
  2688. to array, or slice. There are two variants: a simple form that specifies a low
  2689. and high bound, and a full form that also specifies a bound on the capacity.
  2690. </p>
  2691. <h4>Simple slice expressions</h4>
  2692. <p>
  2693. For a string, array, pointer to array, or slice <code>a</code>, the primary expression
  2694. </p>
  2695. <pre>
  2696. a[low : high]
  2697. </pre>
  2698. <p>
  2699. constructs a substring or slice. The <i>indices</i> <code>low</code> and
  2700. <code>high</code> select which elements of operand <code>a</code> appear
  2701. in the result. The result has indices starting at 0 and length equal to
  2702. <code>high</code>&nbsp;-&nbsp;<code>low</code>.
  2703. After slicing the array <code>a</code>
  2704. </p>
  2705. <pre>
  2706. a := [5]int{1, 2, 3, 4, 5}
  2707. s := a[1:4]
  2708. </pre>
  2709. <p>
  2710. the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
  2711. </p>
  2712. <pre>
  2713. s[0] == 2
  2714. s[1] == 3
  2715. s[2] == 4
  2716. </pre>
  2717. <p>
  2718. For convenience, any of the indices may be omitted. A missing <code>low</code>
  2719. index defaults to zero; a missing <code>high</code> index defaults to the length of the
  2720. sliced operand:
  2721. </p>
  2722. <pre>
  2723. a[2:] // same as a[2 : len(a)]
  2724. a[:3] // same as a[0 : 3]
  2725. a[:] // same as a[0 : len(a)]
  2726. </pre>
  2727. <p>
  2728. If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
  2729. <code>(*a)[low : high]</code>.
  2730. </p>
  2731. <p>
  2732. For arrays or strings, the indices are <i>in range</i> if
  2733. <code>0</code> &lt;= <code>low</code> &lt;= <code>high</code> &lt;= <code>len(a)</code>,
  2734. otherwise they are <i>out of range</i>.
  2735. For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
  2736. A <a href="#Constants">constant</a> index must be non-negative and
  2737. <a href="#Representability">representable</a> by a value of type
  2738. <code>int</code>; for arrays or constant strings, constant indices must also be in range.
  2739. If both indices are constant, they must satisfy <code>low &lt;= high</code>.
  2740. If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
  2741. </p>
  2742. <p>
  2743. Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
  2744. the result of the slice operation is a non-constant value of the same type as the operand.
  2745. For untyped string operands the result is a non-constant value of type <code>string</code>.
  2746. If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
  2747. and the result of the slice operation is a slice with the same element type as the array.
  2748. </p>
  2749. <p>
  2750. If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
  2751. is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying
  2752. array with the operand.
  2753. </p>
  2754. <pre>
  2755. var a [10]int
  2756. s1 := a[3:7] // underlying array of s1 is array a; &amp;s1[2] == &amp;a[5]
  2757. s2 := s1[1:4] // underlying array of s2 is underlying array of s1 which is array a; &amp;s2[1] == &amp;a[5]
  2758. s2[1] = 42 // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element
  2759. </pre>
  2760. <h4>Full slice expressions</h4>
  2761. <p>
  2762. For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression
  2763. </p>
  2764. <pre>
  2765. a[low : high : max]
  2766. </pre>
  2767. <p>
  2768. constructs a slice of the same type, and with the same length and elements as the simple slice
  2769. expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
  2770. by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
  2771. After slicing the array <code>a</code>
  2772. </p>
  2773. <pre>
  2774. a := [5]int{1, 2, 3, 4, 5}
  2775. t := a[1:3:5]
  2776. </pre>
  2777. <p>
  2778. the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
  2779. </p>
  2780. <pre>
  2781. t[0] == 2
  2782. t[1] == 3
  2783. </pre>
  2784. <p>
  2785. As for simple slice expressions, if <code>a</code> is a pointer to an array,
  2786. <code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
  2787. If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
  2788. </p>
  2789. <p>
  2790. The indices are <i>in range</i> if <code>0 &lt;= low &lt;= high &lt;= max &lt;= cap(a)</code>,
  2791. otherwise they are <i>out of range</i>.
  2792. A <a href="#Constants">constant</a> index must be non-negative and
  2793. <a href="#Representability">representable</a> by a value of type
  2794. <code>int</code>; for arrays, constant indices must also be in range.
  2795. If multiple indices are constant, the constants that are present must be in range relative to each
  2796. other.
  2797. If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
  2798. </p>
  2799. <h3 id="Type_assertions">Type assertions</h3>
  2800. <p>
  2801. For an expression <code>x</code> of <a href="#Interface_types">interface type</a>
  2802. and a type <code>T</code>, the primary expression
  2803. </p>
  2804. <pre>
  2805. x.(T)
  2806. </pre>
  2807. <p>
  2808. asserts that <code>x</code> is not <code>nil</code>
  2809. and that the value stored in <code>x</code> is of type <code>T</code>.
  2810. The notation <code>x.(T)</code> is called a <i>type assertion</i>.
  2811. </p>
  2812. <p>
  2813. More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
  2814. that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
  2815. to the type <code>T</code>.
  2816. In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
  2817. otherwise the type assertion is invalid since it is not possible for <code>x</code>
  2818. to store a value of type <code>T</code>.
  2819. If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
  2820. of <code>x</code> implements the interface <code>T</code>.
  2821. </p>
  2822. <p>
  2823. If the type assertion holds, the value of the expression is the value
  2824. stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
  2825. a <a href="#Run_time_panics">run-time panic</a> occurs.
  2826. In other words, even though the dynamic type of <code>x</code>
  2827. is known only at run time, the type of <code>x.(T)</code> is
  2828. known to be <code>T</code> in a correct program.
  2829. </p>
  2830. <pre>
  2831. var x interface{} = 7 // x has dynamic type int and value 7
  2832. i := x.(int) // i has type int and value 7
  2833. type I interface { m() }
  2834. func f(y I) {
  2835. s := y.(string) // illegal: string does not implement I (missing method m)
  2836. r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
  2837. }
  2838. </pre>
  2839. <p>
  2840. A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
  2841. </p>
  2842. <pre>
  2843. v, ok = x.(T)
  2844. v, ok := x.(T)
  2845. var v, ok = x.(T)
  2846. var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool
  2847. </pre>
  2848. <p>
  2849. yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
  2850. if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
  2851. the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
  2852. No <a href="#Run_time_panics">run-time panic</a> occurs in this case.
  2853. </p>
  2854. <h3 id="Calls">Calls</h3>
  2855. <p>
  2856. Given an expression <code>f</code> of function type
  2857. <code>F</code>,
  2858. </p>
  2859. <pre>
  2860. f(a1, a2, … an)
  2861. </pre>
  2862. <p>
  2863. calls <code>f</code> with arguments <code>a1, a2, … an</code>.
  2864. Except for one special case, arguments must be single-valued expressions
  2865. <a href="#Assignability">assignable</a> to the parameter types of
  2866. <code>F</code> and are evaluated before the function is called.
  2867. The type of the expression is the result type
  2868. of <code>F</code>.
  2869. A method invocation is similar but the method itself
  2870. is specified as a selector upon a value of the receiver type for
  2871. the method.
  2872. </p>
  2873. <pre>
  2874. math.Atan2(x, y) // function call
  2875. var pt *Point
  2876. pt.Scale(3.5) // method call with receiver pt
  2877. </pre>
  2878. <p>
  2879. In a function call, the function value and arguments are evaluated in
  2880. <a href="#Order_of_evaluation">the usual order</a>.
  2881. After they are evaluated, the parameters of the call are passed by value to the function
  2882. and the called function begins execution.
  2883. The return parameters of the function are passed by value
  2884. back to the caller when the function returns.
  2885. </p>
  2886. <p>
  2887. Calling a <code>nil</code> function value
  2888. causes a <a href="#Run_time_panics">run-time panic</a>.
  2889. </p>
  2890. <p>
  2891. As a special case, if the return values of a function or method
  2892. <code>g</code> are equal in number and individually
  2893. assignable to the parameters of another function or method
  2894. <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
  2895. will invoke <code>f</code> after binding the return values of
  2896. <code>g</code> to the parameters of <code>f</code> in order. The call
  2897. of <code>f</code> must contain no parameters other than the call of <code>g</code>,
  2898. and <code>g</code> must have at least one return value.
  2899. If <code>f</code> has a final <code>...</code> parameter, it is
  2900. assigned the return values of <code>g</code> that remain after
  2901. assignment of regular parameters.
  2902. </p>
  2903. <pre>
  2904. func Split(s string, pos int) (string, string) {
  2905. return s[0:pos], s[pos:]
  2906. }
  2907. func Join(s, t string) string {
  2908. return s + t
  2909. }
  2910. if Join(Split(value, len(value)/2)) != value {
  2911. log.Panic("test fails")
  2912. }
  2913. </pre>
  2914. <p>
  2915. A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
  2916. of (the type of) <code>x</code> contains <code>m</code> and the
  2917. argument list can be assigned to the parameter list of <code>m</code>.
  2918. If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&amp;x</code>'s method
  2919. set contains <code>m</code>, <code>x.m()</code> is shorthand
  2920. for <code>(&amp;x).m()</code>:
  2921. </p>
  2922. <pre>
  2923. var p Point
  2924. p.Scale(3.5)
  2925. </pre>
  2926. <p>
  2927. There is no distinct method type and there are no method literals.
  2928. </p>
  2929. <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
  2930. <p>
  2931. If <code>f</code> is <a href="#Function_types">variadic</a> with a final
  2932. parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
  2933. the type of <code>p</code> is equivalent to type <code>[]T</code>.
  2934. If <code>f</code> is invoked with no actual arguments for <code>p</code>,
  2935. the value passed to <code>p</code> is <code>nil</code>.
  2936. Otherwise, the value passed is a new slice
  2937. of type <code>[]T</code> with a new underlying array whose successive elements
  2938. are the actual arguments, which all must be <a href="#Assignability">assignable</a>
  2939. to <code>T</code>. The length and capacity of the slice is therefore
  2940. the number of arguments bound to <code>p</code> and may differ for each
  2941. call site.
  2942. </p>
  2943. <p>
  2944. Given the function and calls
  2945. </p>
  2946. <pre>
  2947. func Greeting(prefix string, who ...string)
  2948. Greeting("nobody")
  2949. Greeting("hello:", "Joe", "Anna", "Eileen")
  2950. </pre>
  2951. <p>
  2952. within <code>Greeting</code>, <code>who</code> will have the value
  2953. <code>nil</code> in the first call, and
  2954. <code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
  2955. </p>
  2956. <p>
  2957. If the final argument is assignable to a slice type <code>[]T</code> and
  2958. is followed by <code>...</code>, it is passed unchanged as the value
  2959. for a <code>...T</code> parameter. In this case no new slice is created.
  2960. </p>
  2961. <p>
  2962. Given the slice <code>s</code> and call
  2963. </p>
  2964. <pre>
  2965. s := []string{"James", "Jasmine"}
  2966. Greeting("goodbye:", s...)
  2967. </pre>
  2968. <p>
  2969. within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
  2970. with the same underlying array.
  2971. </p>
  2972. <h3 id="Operators">Operators</h3>
  2973. <p>
  2974. Operators combine operands into expressions.
  2975. </p>
  2976. <pre class="ebnf">
  2977. Expression = UnaryExpr | Expression binary_op Expression .
  2978. UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
  2979. binary_op = "||" | "&amp;&amp;" | rel_op | add_op | mul_op .
  2980. rel_op = "==" | "!=" | "&lt;" | "&lt;=" | ">" | ">=" .
  2981. add_op = "+" | "-" | "|" | "^" .
  2982. mul_op = "*" | "/" | "%" | "&lt;&lt;" | "&gt;&gt;" | "&amp;" | "&amp;^" .
  2983. unary_op = "+" | "-" | "!" | "^" | "*" | "&amp;" | "&lt;-" .
  2984. </pre>
  2985. <p>
  2986. Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
  2987. For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
  2988. unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
  2989. For operations involving constants only, see the section on
  2990. <a href="#Constant_expressions">constant expressions</a>.
  2991. </p>
  2992. <p>
  2993. Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
  2994. and the other operand is not, the constant is implicitly <a href="#Conversions">converted</a>
  2995. to the type of the other operand.
  2996. </p>
  2997. <p>
  2998. The right operand in a shift expression must have integer type
  2999. or be an untyped constant <a href="#Representability">representable</a> by a
  3000. value of type <code>uint</code>.
  3001. If the left operand of a non-constant shift expression is an untyped constant,
  3002. it is first implicitly converted to the type it would assume if the shift expression were
  3003. replaced by its left operand alone.
  3004. </p>
  3005. <pre>
  3006. var a [1024]byte
  3007. var s uint = 33
  3008. // The results of the following examples are given for 64-bit ints.
  3009. var i = 1&lt;&lt;s // 1 has type int
  3010. var j int32 = 1&lt;&lt;s // 1 has type int32; j == 0
  3011. var k = uint64(1&lt;&lt;s) // 1 has type uint64; k == 1&lt;&lt;33
  3012. var m int = 1.0&lt;&lt;s // 1.0 has type int; m == 1&lt;&lt;33
  3013. var n = 1.0&lt;&lt;s == j // 1.0 has type int32; n == true
  3014. var o = 1&lt;&lt;s == 2&lt;&lt;s // 1 and 2 have type int; o == false
  3015. var p = 1&lt;&lt;s == 1&lt;&lt;33 // 1 has type int; p == true
  3016. var u = 1.0&lt;&lt;s // illegal: 1.0 has type float64, cannot shift
  3017. var u1 = 1.0&lt;&lt;s != 0 // illegal: 1.0 has type float64, cannot shift
  3018. var u2 = 1&lt;&lt;s != 1.0 // illegal: 1 has type float64, cannot shift
  3019. var v float32 = 1&lt;&lt;s // illegal: 1 has type float32, cannot shift
  3020. var w int64 = 1.0&lt;&lt;33 // 1.0&lt;&lt;33 is a constant shift expression; w == 1&lt;&lt;33
  3021. var x = a[1.0&lt;&lt;s] // panics: 1.0 has type int, but 1&lt;&lt;33 overflows array bounds
  3022. var b = make([]byte, 1.0&lt;&lt;s) // 1.0 has type int; len(b) == 1&lt;&lt;33
  3023. // The results of the following examples are given for 32-bit ints,
  3024. // which means the shifts will overflow.
  3025. var mm int = 1.0&lt;&lt;s // 1.0 has type int; mm == 0
  3026. var oo = 1&lt;&lt;s == 2&lt;&lt;s // 1 and 2 have type int; oo == true
  3027. var pp = 1&lt;&lt;s == 1&lt;&lt;33 // illegal: 1 has type int, but 1&lt;&lt;33 overflows int
  3028. var xx = a[1.0&lt;&lt;s] // 1.0 has type int; xx == a[0]
  3029. var bb = make([]byte, 1.0&lt;&lt;s) // 1.0 has type int; len(bb) == 0
  3030. </pre>
  3031. <h4 id="Operator_precedence">Operator precedence</h4>
  3032. <p>
  3033. Unary operators have the highest precedence.
  3034. As the <code>++</code> and <code>--</code> operators form
  3035. statements, not expressions, they fall
  3036. outside the operator hierarchy.
  3037. As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
  3038. </p>
  3039. <p>
  3040. There are five precedence levels for binary operators.
  3041. Multiplication operators bind strongest, followed by addition
  3042. operators, comparison operators, <code>&amp;&amp;</code> (logical AND),
  3043. and finally <code>||</code> (logical OR):
  3044. </p>
  3045. <pre class="grammar">
  3046. Precedence Operator
  3047. 5 * / % &lt;&lt; &gt;&gt; &amp; &amp;^
  3048. 4 + - | ^
  3049. 3 == != &lt; &lt;= &gt; &gt;=
  3050. 2 &amp;&amp;
  3051. 1 ||
  3052. </pre>
  3053. <p>
  3054. Binary operators of the same precedence associate from left to right.
  3055. For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
  3056. </p>
  3057. <pre>
  3058. +x
  3059. 23 + 3*x[i]
  3060. x &lt;= f()
  3061. ^a &gt;&gt; b
  3062. f() || g()
  3063. x == y+1 &amp;&amp; &lt;-chanInt &gt; 0
  3064. </pre>
  3065. <h3 id="Arithmetic_operators">Arithmetic operators</h3>
  3066. <p>
  3067. Arithmetic operators apply to numeric values and yield a result of the same
  3068. type as the first operand. The four standard arithmetic operators (<code>+</code>,
  3069. <code>-</code>, <code>*</code>, <code>/</code>) apply to integer,
  3070. floating-point, and complex types; <code>+</code> also applies to strings.
  3071. The bitwise logical and shift operators apply to integers only.
  3072. </p>
  3073. <pre class="grammar">
  3074. + sum integers, floats, complex values, strings
  3075. - difference integers, floats, complex values
  3076. * product integers, floats, complex values
  3077. / quotient integers, floats, complex values
  3078. % remainder integers
  3079. &amp; bitwise AND integers
  3080. | bitwise OR integers
  3081. ^ bitwise XOR integers
  3082. &amp;^ bit clear (AND NOT) integers
  3083. &lt;&lt; left shift integer &lt;&lt; integer &gt;= 0
  3084. &gt;&gt; right shift integer &gt;&gt; integer &gt;= 0
  3085. </pre>
  3086. <h4 id="Integer_operators">Integer operators</h4>
  3087. <p>
  3088. For two integer values <code>x</code> and <code>y</code>, the integer quotient
  3089. <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
  3090. relationships:
  3091. </p>
  3092. <pre>
  3093. x = q*y + r and |r| &lt; |y|
  3094. </pre>
  3095. <p>
  3096. with <code>x / y</code> truncated towards zero
  3097. (<a href="https://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
  3098. </p>
  3099. <pre>
  3100. x y x / y x % y
  3101. 5 3 1 2
  3102. -5 3 -1 -2
  3103. 5 -3 -1 2
  3104. -5 -3 1 -2
  3105. </pre>
  3106. <p>
  3107. The one exception to this rule is that if the dividend <code>x</code> is
  3108. the most negative value for the int type of <code>x</code>, the quotient
  3109. <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>)
  3110. due to two's-complement <a href="#Integer_overflow">integer overflow</a>:
  3111. </p>
  3112. <pre>
  3113. x, q
  3114. int8 -128
  3115. int16 -32768
  3116. int32 -2147483648
  3117. int64 -9223372036854775808
  3118. </pre>
  3119. <p>
  3120. If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
  3121. If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
  3122. If the dividend is non-negative and the divisor is a constant power of 2,
  3123. the division may be replaced by a right shift, and computing the remainder may
  3124. be replaced by a bitwise AND operation:
  3125. </p>
  3126. <pre>
  3127. x x / 4 x % 4 x &gt;&gt; 2 x &amp; 3
  3128. 11 2 3 2 3
  3129. -11 -2 -3 -3 1
  3130. </pre>
  3131. <p>
  3132. The shift operators shift the left operand by the shift count specified by the
  3133. right operand, which must be non-negative. If the shift count is negative at run time,
  3134. a <a href="#Run_time_panics">run-time panic</a> occurs.
  3135. The shift operators implement arithmetic shifts if the left operand is a signed
  3136. integer and logical shifts if it is an unsigned integer.
  3137. There is no upper limit on the shift count. Shifts behave
  3138. as if the left operand is shifted <code>n</code> times by 1 for a shift
  3139. count of <code>n</code>.
  3140. As a result, <code>x &lt;&lt; 1</code> is the same as <code>x*2</code>
  3141. and <code>x &gt;&gt; 1</code> is the same as
  3142. <code>x/2</code> but truncated towards negative infinity.
  3143. </p>
  3144. <p>
  3145. For integer operands, the unary operators
  3146. <code>+</code>, <code>-</code>, and <code>^</code> are defined as
  3147. follows:
  3148. </p>
  3149. <pre class="grammar">
  3150. +x is 0 + x
  3151. -x negation is 0 - x
  3152. ^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x
  3153. and m = -1 for signed x
  3154. </pre>
  3155. <h4 id="Integer_overflow">Integer overflow</h4>
  3156. <p>
  3157. For unsigned integer values, the operations <code>+</code>,
  3158. <code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> are
  3159. computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
  3160. the <a href="#Numeric_types">unsigned integer</a>'s type.
  3161. Loosely speaking, these unsigned integer operations
  3162. discard high bits upon overflow, and programs may rely on "wrap around".
  3163. </p>
  3164. <p>
  3165. For signed integers, the operations <code>+</code>,
  3166. <code>-</code>, <code>*</code>, <code>/</code>, and <code>&lt;&lt;</code> may legally
  3167. overflow and the resulting value exists and is deterministically defined
  3168. by the signed integer representation, the operation, and its operands.
  3169. Overflow does not cause a <a href="#Run_time_panics">run-time panic</a>.
  3170. A compiler may not optimize code under the assumption that overflow does
  3171. not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
  3172. </p>
  3173. <h4 id="Floating_point_operators">Floating-point operators</h4>
  3174. <p>
  3175. For floating-point and complex numbers,
  3176. <code>+x</code> is the same as <code>x</code>,
  3177. while <code>-x</code> is the negation of <code>x</code>.
  3178. The result of a floating-point or complex division by zero is not specified beyond the
  3179. IEEE 754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
  3180. occurs is implementation-specific.
  3181. </p>
  3182. <p>
  3183. An implementation may combine multiple floating-point operations into a single
  3184. fused operation, possibly across statements, and produce a result that differs
  3185. from the value obtained by executing and rounding the instructions individually.
  3186. An explicit floating-point type <a href="#Conversions">conversion</a> rounds to
  3187. the precision of the target type, preventing fusion that would discard that rounding.
  3188. </p>
  3189. <p>
  3190. For instance, some architectures provide a "fused multiply and add" (FMA) instruction
  3191. that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>.
  3192. These examples show when a Go implementation can use that instruction:
  3193. </p>
  3194. <pre>
  3195. // FMA allowed for computing r, because x*y is not explicitly rounded:
  3196. r = x*y + z
  3197. r = z; r += x*y
  3198. t = x*y; r = t + z
  3199. *p = x*y; r = *p + z
  3200. r = x*y + float64(z)
  3201. // FMA disallowed for computing r, because it would omit rounding of x*y:
  3202. r = float64(x*y) + z
  3203. r = z; r += float64(x*y)
  3204. t = float64(x*y); r = t + z
  3205. </pre>
  3206. <h4 id="String_concatenation">String concatenation</h4>
  3207. <p>
  3208. Strings can be concatenated using the <code>+</code> operator
  3209. or the <code>+=</code> assignment operator:
  3210. </p>
  3211. <pre>
  3212. s := "hi" + string(c)
  3213. s += " and good bye"
  3214. </pre>
  3215. <p>
  3216. String addition creates a new string by concatenating the operands.
  3217. </p>
  3218. <h3 id="Comparison_operators">Comparison operators</h3>
  3219. <p>
  3220. Comparison operators compare two operands and yield an untyped boolean value.
  3221. </p>
  3222. <pre class="grammar">
  3223. == equal
  3224. != not equal
  3225. &lt; less
  3226. &lt;= less or equal
  3227. &gt; greater
  3228. &gt;= greater or equal
  3229. </pre>
  3230. <p>
  3231. In any comparison, the first operand
  3232. must be <a href="#Assignability">assignable</a>
  3233. to the type of the second operand, or vice versa.
  3234. </p>
  3235. <p>
  3236. The equality operators <code>==</code> and <code>!=</code> apply
  3237. to operands that are <i>comparable</i>.
  3238. The ordering operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code>
  3239. apply to operands that are <i>ordered</i>.
  3240. These terms and the result of the comparisons are defined as follows:
  3241. </p>
  3242. <ul>
  3243. <li>
  3244. Boolean values are comparable.
  3245. Two boolean values are equal if they are either both
  3246. <code>true</code> or both <code>false</code>.
  3247. </li>
  3248. <li>
  3249. Integer values are comparable and ordered, in the usual way.
  3250. </li>
  3251. <li>
  3252. Floating-point values are comparable and ordered,
  3253. as defined by the IEEE 754 standard.
  3254. </li>
  3255. <li>
  3256. Complex values are comparable.
  3257. Two complex values <code>u</code> and <code>v</code> are
  3258. equal if both <code>real(u) == real(v)</code> and
  3259. <code>imag(u) == imag(v)</code>.
  3260. </li>
  3261. <li>
  3262. String values are comparable and ordered, lexically byte-wise.
  3263. </li>
  3264. <li>
  3265. Pointer values are comparable.
  3266. Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
  3267. Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
  3268. </li>
  3269. <li>
  3270. Channel values are comparable.
  3271. Two channel values are equal if they were created by the same call to
  3272. <a href="#Making_slices_maps_and_channels"><code>make</code></a>
  3273. or if both have value <code>nil</code>.
  3274. </li>
  3275. <li>
  3276. Interface values are comparable.
  3277. Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
  3278. and equal dynamic values or if both have value <code>nil</code>.
  3279. </li>
  3280. <li>
  3281. A value <code>x</code> of non-interface type <code>X</code> and
  3282. a value <code>t</code> of interface type <code>T</code> are comparable when values
  3283. of type <code>X</code> are comparable and
  3284. <code>X</code> implements <code>T</code>.
  3285. They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
  3286. and <code>t</code>'s dynamic value is equal to <code>x</code>.
  3287. </li>
  3288. <li>
  3289. Struct values are comparable if all their fields are comparable.
  3290. Two struct values are equal if their corresponding
  3291. non-<a href="#Blank_identifier">blank</a> fields are equal.
  3292. </li>
  3293. <li>
  3294. Array values are comparable if values of the array element type are comparable.
  3295. Two array values are equal if their corresponding elements are equal.
  3296. </li>
  3297. </ul>
  3298. <p>
  3299. A comparison of two interface values with identical dynamic types
  3300. causes a <a href="#Run_time_panics">run-time panic</a> if values
  3301. of that type are not comparable. This behavior applies not only to direct interface
  3302. value comparisons but also when comparing arrays of interface values
  3303. or structs with interface-valued fields.
  3304. </p>
  3305. <p>
  3306. Slice, map, and function values are not comparable.
  3307. However, as a special case, a slice, map, or function value may
  3308. be compared to the predeclared identifier <code>nil</code>.
  3309. Comparison of pointer, channel, and interface values to <code>nil</code>
  3310. is also allowed and follows from the general rules above.
  3311. </p>
  3312. <pre>
  3313. const c = 3 &lt; 4 // c is the untyped boolean constant true
  3314. type MyBool bool
  3315. var x, y int
  3316. var (
  3317. // The result of a comparison is an untyped boolean.
  3318. // The usual assignment rules apply.
  3319. b3 = x == y // b3 has type bool
  3320. b4 bool = x == y // b4 has type bool
  3321. b5 MyBool = x == y // b5 has type MyBool
  3322. )
  3323. </pre>
  3324. <h3 id="Logical_operators">Logical operators</h3>
  3325. <p>
  3326. Logical operators apply to <a href="#Boolean_types">boolean</a> values
  3327. and yield a result of the same type as the operands.
  3328. The right operand is evaluated conditionally.
  3329. </p>
  3330. <pre class="grammar">
  3331. &amp;&amp; conditional AND p &amp;&amp; q is "if p then q else false"
  3332. || conditional OR p || q is "if p then true else q"
  3333. ! NOT !p is "not p"
  3334. </pre>
  3335. <h3 id="Address_operators">Address operators</h3>
  3336. <p>
  3337. For an operand <code>x</code> of type <code>T</code>, the address operation
  3338. <code>&amp;x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
  3339. The operand must be <i>addressable</i>,
  3340. that is, either a variable, pointer indirection, or slice indexing
  3341. operation; or a field selector of an addressable struct operand;
  3342. or an array indexing operation of an addressable array.
  3343. As an exception to the addressability requirement, <code>x</code> may also be a
  3344. (possibly parenthesized)
  3345. <a href="#Composite_literals">composite literal</a>.
  3346. If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
  3347. then the evaluation of <code>&amp;x</code> does too.
  3348. </p>
  3349. <p>
  3350. For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
  3351. indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed
  3352. to by <code>x</code>.
  3353. If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
  3354. will cause a <a href="#Run_time_panics">run-time panic</a>.
  3355. </p>
  3356. <pre>
  3357. &amp;x
  3358. &amp;a[f(2)]
  3359. &amp;Point{2, 3}
  3360. *p
  3361. *pf(x)
  3362. var x *int = nil
  3363. *x // causes a run-time panic
  3364. &amp;*x // causes a run-time panic
  3365. </pre>
  3366. <h3 id="Receive_operator">Receive operator</h3>
  3367. <p>
  3368. For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
  3369. the value of the receive operation <code>&lt;-ch</code> is the value received
  3370. from the channel <code>ch</code>. The channel direction must permit receive operations,
  3371. and the type of the receive operation is the element type of the channel.
  3372. The expression blocks until a value is available.
  3373. Receiving from a <code>nil</code> channel blocks forever.
  3374. A receive operation on a <a href="#Close">closed</a> channel can always proceed
  3375. immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
  3376. after any previously sent values have been received.
  3377. </p>
  3378. <pre>
  3379. v1 := &lt;-ch
  3380. v2 = &lt;-ch
  3381. f(&lt;-ch)
  3382. &lt;-strobe // wait until clock pulse and discard received value
  3383. </pre>
  3384. <p>
  3385. A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
  3386. </p>
  3387. <pre>
  3388. x, ok = &lt;-ch
  3389. x, ok := &lt;-ch
  3390. var x, ok = &lt;-ch
  3391. var x, ok T = &lt;-ch
  3392. </pre>
  3393. <p>
  3394. yields an additional untyped boolean result reporting whether the
  3395. communication succeeded. The value of <code>ok</code> is <code>true</code>
  3396. if the value received was delivered by a successful send operation to the
  3397. channel, or <code>false</code> if it is a zero value generated because the
  3398. channel is closed and empty.
  3399. </p>
  3400. <h3 id="Conversions">Conversions</h3>
  3401. <p>
  3402. A conversion changes the <a href="#Types">type</a> of an expression
  3403. to the type specified by the conversion.
  3404. A conversion may appear literally in the source, or it may be <i>implied</i>
  3405. by the context in which an expression appears.
  3406. </p>
  3407. <p>
  3408. An <i>explicit</i> conversion is an expression of the form <code>T(x)</code>
  3409. where <code>T</code> is a type and <code>x</code> is an expression
  3410. that can be converted to type <code>T</code>.
  3411. </p>
  3412. <pre class="ebnf">
  3413. Conversion = Type "(" Expression [ "," ] ")" .
  3414. </pre>
  3415. <p>
  3416. If the type starts with the operator <code>*</code> or <code>&lt;-</code>,
  3417. or if the type starts with the keyword <code>func</code>
  3418. and has no result list, it must be parenthesized when
  3419. necessary to avoid ambiguity:
  3420. </p>
  3421. <pre>
  3422. *Point(p) // same as *(Point(p))
  3423. (*Point)(p) // p is converted to *Point
  3424. &lt;-chan int(c) // same as &lt;-(chan int(c))
  3425. (&lt;-chan int)(c) // c is converted to &lt;-chan int
  3426. func()(x) // function signature func() x
  3427. (func())(x) // x is converted to func()
  3428. (func() int)(x) // x is converted to func() int
  3429. func() int(x) // x is converted to func() int (unambiguous)
  3430. </pre>
  3431. <p>
  3432. A <a href="#Constants">constant</a> value <code>x</code> can be converted to
  3433. type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a>
  3434. by a value of <code>T</code>.
  3435. As a special case, an integer constant <code>x</code> can be explicitly converted to a
  3436. <a href="#String_types">string type</a> using the
  3437. <a href="#Conversions_to_and_from_a_string_type">same rule</a>
  3438. as for non-constant <code>x</code>.
  3439. </p>
  3440. <p>
  3441. Converting a constant yields a typed constant as result.
  3442. </p>
  3443. <pre>
  3444. uint(iota) // iota value of type uint
  3445. float32(2.718281828) // 2.718281828 of type float32
  3446. complex128(1) // 1.0 + 0.0i of type complex128
  3447. float32(0.49999999) // 0.5 of type float32
  3448. float64(-1e-1000) // 0.0 of type float64
  3449. string('x') // "x" of type string
  3450. string(0x266c) // "♬" of type string
  3451. MyString("foo" + "bar") // "foobar" of type MyString
  3452. string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
  3453. (*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
  3454. int(1.2) // illegal: 1.2 cannot be represented as an int
  3455. string(65.0) // illegal: 65.0 is not an integer constant
  3456. </pre>
  3457. <p>
  3458. A non-constant value <code>x</code> can be converted to type <code>T</code>
  3459. in any of these cases:
  3460. </p>
  3461. <ul>
  3462. <li>
  3463. <code>x</code> is <a href="#Assignability">assignable</a>
  3464. to <code>T</code>.
  3465. </li>
  3466. <li>
  3467. ignoring struct tags (see below),
  3468. <code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a>
  3469. <a href="#Types">underlying types</a>.
  3470. </li>
  3471. <li>
  3472. ignoring struct tags (see below),
  3473. <code>x</code>'s type and <code>T</code> are pointer types
  3474. that are not <a href="#Type_definitions">defined types</a>,
  3475. and their pointer base types have identical underlying types.
  3476. </li>
  3477. <li>
  3478. <code>x</code>'s type and <code>T</code> are both integer or floating
  3479. point types.
  3480. </li>
  3481. <li>
  3482. <code>x</code>'s type and <code>T</code> are both complex types.
  3483. </li>
  3484. <li>
  3485. <code>x</code> is an integer or a slice of bytes or runes
  3486. and <code>T</code> is a string type.
  3487. </li>
  3488. <li>
  3489. <code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
  3490. </li>
  3491. <li>
  3492. <code>x</code> is a slice, <code>T</code> is a pointer to an array,
  3493. and the slice and array types have <a href="#Type_identity">identical</a> element types.
  3494. </li>
  3495. </ul>
  3496. <p>
  3497. <a href="#Struct_types">Struct tags</a> are ignored when comparing struct types
  3498. for identity for the purpose of conversion:
  3499. </p>
  3500. <pre>
  3501. type Person struct {
  3502. Name string
  3503. Address *struct {
  3504. Street string
  3505. City string
  3506. }
  3507. }
  3508. var data *struct {
  3509. Name string `json:"name"`
  3510. Address *struct {
  3511. Street string `json:"street"`
  3512. City string `json:"city"`
  3513. } `json:"address"`
  3514. }
  3515. var person = (*Person)(data) // ignoring tags, the underlying types are identical
  3516. </pre>
  3517. <p>
  3518. Specific rules apply to (non-constant) conversions between numeric types or
  3519. to and from a string type.
  3520. These conversions may change the representation of <code>x</code>
  3521. and incur a run-time cost.
  3522. All other conversions only change the type but not the representation
  3523. of <code>x</code>.
  3524. </p>
  3525. <p>
  3526. There is no linguistic mechanism to convert between pointers and integers.
  3527. The package <a href="#Package_unsafe"><code>unsafe</code></a>
  3528. implements this functionality under
  3529. restricted circumstances.
  3530. </p>
  3531. <h4>Conversions between numeric types</h4>
  3532. <p>
  3533. For the conversion of non-constant numeric values, the following rules apply:
  3534. </p>
  3535. <ol>
  3536. <li>
  3537. When converting between integer types, if the value is a signed integer, it is
  3538. sign extended to implicit infinite precision; otherwise it is zero extended.
  3539. It is then truncated to fit in the result type's size.
  3540. For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
  3541. The conversion always yields a valid value; there is no indication of overflow.
  3542. </li>
  3543. <li>
  3544. When converting a floating-point number to an integer, the fraction is discarded
  3545. (truncation towards zero).
  3546. </li>
  3547. <li>
  3548. When converting an integer or floating-point number to a floating-point type,
  3549. or a complex number to another complex type, the result value is rounded
  3550. to the precision specified by the destination type.
  3551. For instance, the value of a variable <code>x</code> of type <code>float32</code>
  3552. may be stored using additional precision beyond that of an IEEE 754 32-bit number,
  3553. but float32(x) represents the result of rounding <code>x</code>'s value to
  3554. 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
  3555. of precision, but <code>float32(x + 0.1)</code> does not.
  3556. </li>
  3557. </ol>
  3558. <p>
  3559. In all non-constant conversions involving floating-point or complex values,
  3560. if the result type cannot represent the value the conversion
  3561. succeeds but the result value is implementation-dependent.
  3562. </p>
  3563. <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
  3564. <ol>
  3565. <li>
  3566. Converting a signed or unsigned integer value to a string type yields a
  3567. string containing the UTF-8 representation of the integer. Values outside
  3568. the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
  3569. <pre>
  3570. string('a') // "a"
  3571. string(-1) // "\ufffd" == "\xef\xbf\xbd"
  3572. string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
  3573. type MyString string
  3574. MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
  3575. </pre>
  3576. </li>
  3577. <li>
  3578. Converting a slice of bytes to a string type yields
  3579. a string whose successive bytes are the elements of the slice.
  3580. <pre>
  3581. string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
  3582. string([]byte{}) // ""
  3583. string([]byte(nil)) // ""
  3584. type MyBytes []byte
  3585. string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
  3586. </pre>
  3587. </li>
  3588. <li>
  3589. Converting a slice of runes to a string type yields
  3590. a string that is the concatenation of the individual rune values
  3591. converted to strings.
  3592. <pre>
  3593. string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
  3594. string([]rune{}) // ""
  3595. string([]rune(nil)) // ""
  3596. type MyRunes []rune
  3597. string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
  3598. </pre>
  3599. </li>
  3600. <li>
  3601. Converting a value of a string type to a slice of bytes type
  3602. yields a slice whose successive elements are the bytes of the string.
  3603. <pre>
  3604. []byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
  3605. []byte("") // []byte{}
  3606. MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
  3607. </pre>
  3608. </li>
  3609. <li>
  3610. Converting a value of a string type to a slice of runes type
  3611. yields a slice containing the individual Unicode code points of the string.
  3612. <pre>
  3613. []rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
  3614. []rune("") // []rune{}
  3615. MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
  3616. </pre>
  3617. </li>
  3618. </ol>
  3619. <h4 id="Conversions_from_slice_to_array_pointer">Conversions from slice to array pointer</h4>
  3620. <p>
  3621. Converting a slice to an array pointer yields a pointer to the underlying array of the slice.
  3622. If the <a href="#Length_and_capacity">length</a> of the slice is less than the length of the array,
  3623. a <a href="#Run_time_panics">run-time panic</a> occurs.
  3624. </p>
  3625. <pre>
  3626. s := make([]byte, 2, 4)
  3627. s0 := (*[0]byte)(s) // s0 != nil
  3628. s1 := (*[1]byte)(s[1:]) // &amp;s1[0] == &amp;s[1]
  3629. s2 := (*[2]byte)(s) // &amp;s2[0] == &amp;s[0]
  3630. s4 := (*[4]byte)(s) // panics: len([4]byte) > len(s)
  3631. var t []string
  3632. t0 := (*[0]string)(t) // t0 == nil
  3633. t1 := (*[1]string)(t) // panics: len([1]string) > len(t)
  3634. u := make([]byte, 0)
  3635. u0 := (*[0]byte)(u) // u0 != nil
  3636. </pre>
  3637. <h3 id="Constant_expressions">Constant expressions</h3>
  3638. <p>
  3639. Constant expressions may contain only <a href="#Constants">constant</a>
  3640. operands and are evaluated at compile time.
  3641. </p>
  3642. <p>
  3643. Untyped boolean, numeric, and string constants may be used as operands
  3644. wherever it is legal to use an operand of boolean, numeric, or string type,
  3645. respectively.
  3646. </p>
  3647. <p>
  3648. A constant <a href="#Comparison_operators">comparison</a> always yields
  3649. an untyped boolean constant. If the left operand of a constant
  3650. <a href="#Operators">shift expression</a> is an untyped constant, the
  3651. result is an integer constant; otherwise it is a constant of the same
  3652. type as the left operand, which must be of
  3653. <a href="#Numeric_types">integer type</a>.
  3654. </p>
  3655. <p>
  3656. Any other operation on untyped constants results in an untyped constant of the
  3657. same kind; that is, a boolean, integer, floating-point, complex, or string
  3658. constant.
  3659. If the untyped operands of a binary operation (other than a shift) are of
  3660. different kinds, the result is of the operand's kind that appears later in this
  3661. list: integer, rune, floating-point, complex.
  3662. For example, an untyped integer constant divided by an
  3663. untyped complex constant yields an untyped complex constant.
  3664. </p>
  3665. <pre>
  3666. const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)
  3667. const b = 15 / 4 // b == 3 (untyped integer constant)
  3668. const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)
  3669. const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)
  3670. const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)
  3671. const d = 1 &lt;&lt; 3.0 // d == 8 (untyped integer constant)
  3672. const e = 1.0 &lt;&lt; 3 // e == 8 (untyped integer constant)
  3673. const f = int32(1) &lt;&lt; 33 // illegal (constant 8589934592 overflows int32)
  3674. const g = float64(2) &gt;&gt; 1 // illegal (float64(2) is a typed floating-point constant)
  3675. const h = "foo" &gt; "bar" // h == true (untyped boolean constant)
  3676. const j = true // j == true (untyped boolean constant)
  3677. const k = 'w' + 1 // k == 'x' (untyped rune constant)
  3678. const l = "hi" // l == "hi" (untyped string constant)
  3679. const m = string(k) // m == "x" (type string)
  3680. const Σ = 1 - 0.707i // (untyped complex constant)
  3681. const Δ = Σ + 2.0e-4 // (untyped complex constant)
  3682. const Φ = iota*1i - 1/1i // (untyped complex constant)
  3683. </pre>
  3684. <p>
  3685. Applying the built-in function <code>complex</code> to untyped
  3686. integer, rune, or floating-point constants yields
  3687. an untyped complex constant.
  3688. </p>
  3689. <pre>
  3690. const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
  3691. const iΘ = complex(0, Θ) // iΘ == 1i (type complex128)
  3692. </pre>
  3693. <p>
  3694. Constant expressions are always evaluated exactly; intermediate values and the
  3695. constants themselves may require precision significantly larger than supported
  3696. by any predeclared type in the language. The following are legal declarations:
  3697. </p>
  3698. <pre>
  3699. const Huge = 1 &lt;&lt; 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
  3700. const Four int8 = Huge &gt;&gt; 98 // Four == 4 (type int8)
  3701. </pre>
  3702. <p>
  3703. The divisor of a constant division or remainder operation must not be zero:
  3704. </p>
  3705. <pre>
  3706. 3.14 / 0.0 // illegal: division by zero
  3707. </pre>
  3708. <p>
  3709. The values of <i>typed</i> constants must always be accurately
  3710. <a href="#Representability">representable</a> by values
  3711. of the constant type. The following constant expressions are illegal:
  3712. </p>
  3713. <pre>
  3714. uint(-1) // -1 cannot be represented as a uint
  3715. int(3.14) // 3.14 cannot be represented as an int
  3716. int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
  3717. Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
  3718. Four * 100 // product 400 cannot be represented as an int8 (type of Four)
  3719. </pre>
  3720. <p>
  3721. The mask used by the unary bitwise complement operator <code>^</code> matches
  3722. the rule for non-constants: the mask is all 1s for unsigned constants
  3723. and -1 for signed and untyped constants.
  3724. </p>
  3725. <pre>
  3726. ^1 // untyped integer constant, equal to -2
  3727. uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8
  3728. ^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
  3729. int8(^1) // same as int8(-2)
  3730. ^int8(1) // same as -1 ^ int8(1) = -2
  3731. </pre>
  3732. <p>
  3733. Implementation restriction: A compiler may use rounding while
  3734. computing untyped floating-point or complex constant expressions; see
  3735. the implementation restriction in the section
  3736. on <a href="#Constants">constants</a>. This rounding may cause a
  3737. floating-point constant expression to be invalid in an integer
  3738. context, even if it would be integral when calculated using infinite
  3739. precision, and vice versa.
  3740. </p>
  3741. <h3 id="Order_of_evaluation">Order of evaluation</h3>
  3742. <p>
  3743. At package level, <a href="#Package_initialization">initialization dependencies</a>
  3744. determine the evaluation order of individual initialization expressions in
  3745. <a href="#Variable_declarations">variable declarations</a>.
  3746. Otherwise, when evaluating the <a href="#Operands">operands</a> of an
  3747. expression, assignment, or
  3748. <a href="#Return_statements">return statement</a>,
  3749. all function calls, method calls, and
  3750. communication operations are evaluated in lexical left-to-right
  3751. order.
  3752. </p>
  3753. <p>
  3754. For example, in the (function-local) assignment
  3755. </p>
  3756. <pre>
  3757. y[f()], ok = g(h(), i()+x[j()], &lt;-c), k()
  3758. </pre>
  3759. <p>
  3760. the function calls and communication happen in the order
  3761. <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
  3762. <code>&lt;-c</code>, <code>g()</code>, and <code>k()</code>.
  3763. However, the order of those events compared to the evaluation
  3764. and indexing of <code>x</code> and the evaluation
  3765. of <code>y</code> is not specified.
  3766. </p>
  3767. <pre>
  3768. a := 1
  3769. f := func() int { a++; return a }
  3770. x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
  3771. m := map[int]int{a: 1, a: 2} // m may be {2: 1} or {2: 2}: evaluation order between the two map assignments is not specified
  3772. n := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified
  3773. </pre>
  3774. <p>
  3775. At package level, initialization dependencies override the left-to-right rule
  3776. for individual initialization expressions, but not for operands within each
  3777. expression:
  3778. </p>
  3779. <pre>
  3780. var a, b, c = f() + v(), g(), sqr(u()) + v()
  3781. func f() int { return c }
  3782. func g() int { return a }
  3783. func sqr(x int) int { return x*x }
  3784. // functions u and v are independent of all other variables and functions
  3785. </pre>
  3786. <p>
  3787. The function calls happen in the order
  3788. <code>u()</code>, <code>sqr()</code>, <code>v()</code>,
  3789. <code>f()</code>, <code>v()</code>, and <code>g()</code>.
  3790. </p>
  3791. <p>
  3792. Floating-point operations within a single expression are evaluated according to
  3793. the associativity of the operators. Explicit parentheses affect the evaluation
  3794. by overriding the default associativity.
  3795. In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
  3796. is performed before adding <code>x</code>.
  3797. </p>
  3798. <h2 id="Statements">Statements</h2>
  3799. <p>
  3800. Statements control execution.
  3801. </p>
  3802. <pre class="ebnf">
  3803. Statement =
  3804. Declaration | LabeledStmt | SimpleStmt |
  3805. GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
  3806. FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
  3807. DeferStmt .
  3808. SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
  3809. </pre>
  3810. <h3 id="Terminating_statements">Terminating statements</h3>
  3811. <p>
  3812. A <i>terminating statement</i> interrupts the regular flow of control in
  3813. a <a href="#Blocks">block</a>. The following statements are terminating:
  3814. </p>
  3815. <ol>
  3816. <li>
  3817. A <a href="#Return_statements">"return"</a> or
  3818. <a href="#Goto_statements">"goto"</a> statement.
  3819. <!-- ul below only for regular layout -->
  3820. <ul> </ul>
  3821. </li>
  3822. <li>
  3823. A call to the built-in function
  3824. <a href="#Handling_panics"><code>panic</code></a>.
  3825. <!-- ul below only for regular layout -->
  3826. <ul> </ul>
  3827. </li>
  3828. <li>
  3829. A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
  3830. <!-- ul below only for regular layout -->
  3831. <ul> </ul>
  3832. </li>
  3833. <li>
  3834. An <a href="#If_statements">"if" statement</a> in which:
  3835. <ul>
  3836. <li>the "else" branch is present, and</li>
  3837. <li>both branches are terminating statements.</li>
  3838. </ul>
  3839. </li>
  3840. <li>
  3841. A <a href="#For_statements">"for" statement</a> in which:
  3842. <ul>
  3843. <li>there are no "break" statements referring to the "for" statement, and</li>
  3844. <li>the loop condition is absent, and</li>
  3845. <li>the "for" statement does not use a range clause.</li>
  3846. </ul>
  3847. </li>
  3848. <li>
  3849. A <a href="#Switch_statements">"switch" statement</a> in which:
  3850. <ul>
  3851. <li>there are no "break" statements referring to the "switch" statement,</li>
  3852. <li>there is a default case, and</li>
  3853. <li>the statement lists in each case, including the default, end in a terminating
  3854. statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
  3855. statement</a>.</li>
  3856. </ul>
  3857. </li>
  3858. <li>
  3859. A <a href="#Select_statements">"select" statement</a> in which:
  3860. <ul>
  3861. <li>there are no "break" statements referring to the "select" statement, and</li>
  3862. <li>the statement lists in each case, including the default if present,
  3863. end in a terminating statement.</li>
  3864. </ul>
  3865. </li>
  3866. <li>
  3867. A <a href="#Labeled_statements">labeled statement</a> labeling
  3868. a terminating statement.
  3869. </li>
  3870. </ol>
  3871. <p>
  3872. All other statements are not terminating.
  3873. </p>
  3874. <p>
  3875. A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
  3876. is not empty and its final non-empty statement is terminating.
  3877. </p>
  3878. <h3 id="Empty_statements">Empty statements</h3>
  3879. <p>
  3880. The empty statement does nothing.
  3881. </p>
  3882. <pre class="ebnf">
  3883. EmptyStmt = .
  3884. </pre>
  3885. <h3 id="Labeled_statements">Labeled statements</h3>
  3886. <p>
  3887. A labeled statement may be the target of a <code>goto</code>,
  3888. <code>break</code> or <code>continue</code> statement.
  3889. </p>
  3890. <pre class="ebnf">
  3891. LabeledStmt = Label ":" Statement .
  3892. Label = identifier .
  3893. </pre>
  3894. <pre>
  3895. Error: log.Panic("error encountered")
  3896. </pre>
  3897. <h3 id="Expression_statements">Expression statements</h3>
  3898. <p>
  3899. With the exception of specific built-in functions,
  3900. function and method <a href="#Calls">calls</a> and
  3901. <a href="#Receive_operator">receive operations</a>
  3902. can appear in statement context. Such statements may be parenthesized.
  3903. </p>
  3904. <pre class="ebnf">
  3905. ExpressionStmt = Expression .
  3906. </pre>
  3907. <p>
  3908. The following built-in functions are not permitted in statement context:
  3909. </p>
  3910. <pre>
  3911. append cap complex imag len make new real
  3912. unsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice
  3913. </pre>
  3914. <pre>
  3915. h(x+y)
  3916. f.Close()
  3917. &lt;-ch
  3918. (&lt;-ch)
  3919. len("foo") // illegal if len is the built-in function
  3920. </pre>
  3921. <h3 id="Send_statements">Send statements</h3>
  3922. <p>
  3923. A send statement sends a value on a channel.
  3924. The channel expression must be of <a href="#Channel_types">channel type</a>,
  3925. the channel direction must permit send operations,
  3926. and the type of the value to be sent must be <a href="#Assignability">assignable</a>
  3927. to the channel's element type.
  3928. </p>
  3929. <pre class="ebnf">
  3930. SendStmt = Channel "&lt;-" Expression .
  3931. Channel = Expression .
  3932. </pre>
  3933. <p>
  3934. Both the channel and the value expression are evaluated before communication
  3935. begins. Communication blocks until the send can proceed.
  3936. A send on an unbuffered channel can proceed if a receiver is ready.
  3937. A send on a buffered channel can proceed if there is room in the buffer.
  3938. A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
  3939. A send on a <code>nil</code> channel blocks forever.
  3940. </p>
  3941. <pre>
  3942. ch &lt;- 3 // send value 3 to channel ch
  3943. </pre>
  3944. <h3 id="IncDec_statements">IncDec statements</h3>
  3945. <p>
  3946. The "++" and "--" statements increment or decrement their operands
  3947. by the untyped <a href="#Constants">constant</a> <code>1</code>.
  3948. As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
  3949. or a map index expression.
  3950. </p>
  3951. <pre class="ebnf">
  3952. IncDecStmt = Expression ( "++" | "--" ) .
  3953. </pre>
  3954. <p>
  3955. The following <a href="#Assignments">assignment statements</a> are semantically
  3956. equivalent:
  3957. </p>
  3958. <pre class="grammar">
  3959. IncDec statement Assignment
  3960. x++ x += 1
  3961. x-- x -= 1
  3962. </pre>
  3963. <h3 id="Assignments">Assignments</h3>
  3964. <pre class="ebnf">
  3965. Assignment = ExpressionList assign_op ExpressionList .
  3966. assign_op = [ add_op | mul_op ] "=" .
  3967. </pre>
  3968. <p>
  3969. Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
  3970. a map index expression, or (for <code>=</code> assignments only) the
  3971. <a href="#Blank_identifier">blank identifier</a>.
  3972. Operands may be parenthesized.
  3973. </p>
  3974. <pre>
  3975. x = 1
  3976. *p = f()
  3977. a[i] = 23
  3978. (k) = &lt;-ch // same as: k = &lt;-ch
  3979. </pre>
  3980. <p>
  3981. An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
  3982. <code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a>
  3983. is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
  3984. <code>(y)</code> but evaluates <code>x</code>
  3985. only once. The <i>op</i><code>=</code> construct is a single token.
  3986. In assignment operations, both the left- and right-hand expression lists
  3987. must contain exactly one single-valued expression, and the left-hand
  3988. expression must not be the blank identifier.
  3989. </p>
  3990. <pre>
  3991. a[i] &lt;&lt;= 2
  3992. i &amp;^= 1&lt;&lt;n
  3993. </pre>
  3994. <p>
  3995. A tuple assignment assigns the individual elements of a multi-valued
  3996. operation to a list of variables. There are two forms. In the
  3997. first, the right hand operand is a single multi-valued expression
  3998. such as a function call, a <a href="#Channel_types">channel</a> or
  3999. <a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>.
  4000. The number of operands on the left
  4001. hand side must match the number of values. For instance, if
  4002. <code>f</code> is a function returning two values,
  4003. </p>
  4004. <pre>
  4005. x, y = f()
  4006. </pre>
  4007. <p>
  4008. assigns the first value to <code>x</code> and the second to <code>y</code>.
  4009. In the second form, the number of operands on the left must equal the number
  4010. of expressions on the right, each of which must be single-valued, and the
  4011. <i>n</i>th expression on the right is assigned to the <i>n</i>th
  4012. operand on the left:
  4013. </p>
  4014. <pre>
  4015. one, two, three = '一', '二', '三'
  4016. </pre>
  4017. <p>
  4018. The <a href="#Blank_identifier">blank identifier</a> provides a way to
  4019. ignore right-hand side values in an assignment:
  4020. </p>
  4021. <pre>
  4022. _ = x // evaluate x but ignore it
  4023. x, _ = f() // evaluate f() but ignore second result value
  4024. </pre>
  4025. <p>
  4026. The assignment proceeds in two phases.
  4027. First, the operands of <a href="#Index_expressions">index expressions</a>
  4028. and <a href="#Address_operators">pointer indirections</a>
  4029. (including implicit pointer indirections in <a href="#Selectors">selectors</a>)
  4030. on the left and the expressions on the right are all
  4031. <a href="#Order_of_evaluation">evaluated in the usual order</a>.
  4032. Second, the assignments are carried out in left-to-right order.
  4033. </p>
  4034. <pre>
  4035. a, b = b, a // exchange a and b
  4036. x := []int{1, 2, 3}
  4037. i := 0
  4038. i, x[i] = 1, 2 // set i = 1, x[0] = 2
  4039. i = 0
  4040. x[i], i = 2, 1 // set x[0] = 2, i = 1
  4041. x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
  4042. x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5.
  4043. type Point struct { x, y int }
  4044. var p *Point
  4045. x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7
  4046. i = 2
  4047. x = []int{3, 5, 7}
  4048. for i, x[i] = range x { // set i, x[2] = 0, x[0]
  4049. break
  4050. }
  4051. // after this loop, i == 0 and x == []int{3, 5, 3}
  4052. </pre>
  4053. <p>
  4054. In assignments, each value must be <a href="#Assignability">assignable</a>
  4055. to the type of the operand to which it is assigned, with the following special cases:
  4056. </p>
  4057. <ol>
  4058. <li>
  4059. Any typed value may be assigned to the blank identifier.
  4060. </li>
  4061. <li>
  4062. If an untyped constant
  4063. is assigned to a variable of interface type or the blank identifier,
  4064. the constant is first implicitly <a href="#Conversions">converted</a> to its
  4065. <a href="#Constants">default type</a>.
  4066. </li>
  4067. <li>
  4068. If an untyped boolean value is assigned to a variable of interface type or
  4069. the blank identifier, it is first implicitly converted to type <code>bool</code>.
  4070. </li>
  4071. </ol>
  4072. <h3 id="If_statements">If statements</h3>
  4073. <p>
  4074. "If" statements specify the conditional execution of two branches
  4075. according to the value of a boolean expression. If the expression
  4076. evaluates to true, the "if" branch is executed, otherwise, if
  4077. present, the "else" branch is executed.
  4078. </p>
  4079. <pre class="ebnf">
  4080. IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
  4081. </pre>
  4082. <pre>
  4083. if x &gt; max {
  4084. x = max
  4085. }
  4086. </pre>
  4087. <p>
  4088. The expression may be preceded by a simple statement, which
  4089. executes before the expression is evaluated.
  4090. </p>
  4091. <pre>
  4092. if x := f(); x &lt; y {
  4093. return x
  4094. } else if x &gt; z {
  4095. return z
  4096. } else {
  4097. return y
  4098. }
  4099. </pre>
  4100. <h3 id="Switch_statements">Switch statements</h3>
  4101. <p>
  4102. "Switch" statements provide multi-way execution.
  4103. An expression or type is compared to the "cases"
  4104. inside the "switch" to determine which branch
  4105. to execute.
  4106. </p>
  4107. <pre class="ebnf">
  4108. SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
  4109. </pre>
  4110. <p>
  4111. There are two forms: expression switches and type switches.
  4112. In an expression switch, the cases contain expressions that are compared
  4113. against the value of the switch expression.
  4114. In a type switch, the cases contain types that are compared against the
  4115. type of a specially annotated switch expression.
  4116. The switch expression is evaluated exactly once in a switch statement.
  4117. </p>
  4118. <h4 id="Expression_switches">Expression switches</h4>
  4119. <p>
  4120. In an expression switch,
  4121. the switch expression is evaluated and
  4122. the case expressions, which need not be constants,
  4123. are evaluated left-to-right and top-to-bottom; the first one that equals the
  4124. switch expression
  4125. triggers execution of the statements of the associated case;
  4126. the other cases are skipped.
  4127. If no case matches and there is a "default" case,
  4128. its statements are executed.
  4129. There can be at most one default case and it may appear anywhere in the
  4130. "switch" statement.
  4131. A missing switch expression is equivalent to the boolean value
  4132. <code>true</code>.
  4133. </p>
  4134. <pre class="ebnf">
  4135. ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
  4136. ExprCaseClause = ExprSwitchCase ":" StatementList .
  4137. ExprSwitchCase = "case" ExpressionList | "default" .
  4138. </pre>
  4139. <p>
  4140. If the switch expression evaluates to an untyped constant, it is first implicitly
  4141. <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>.
  4142. The predeclared untyped value <code>nil</code> cannot be used as a switch expression.
  4143. The switch expression type must be <a href="#Comparison_operators">comparable</a>.
  4144. </p>
  4145. <p>
  4146. If a case expression is untyped, it is first implicitly <a href="#Conversions">converted</a>
  4147. to the type of the switch expression.
  4148. For each (possibly converted) case expression <code>x</code> and the value <code>t</code>
  4149. of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>.
  4150. </p>
  4151. <p>
  4152. In other words, the switch expression is treated as if it were used to declare and
  4153. initialize a temporary variable <code>t</code> without explicit type; it is that
  4154. value of <code>t</code> against which each case expression <code>x</code> is tested
  4155. for equality.
  4156. </p>
  4157. <p>
  4158. In a case or default clause, the last non-empty statement
  4159. may be a (possibly <a href="#Labeled_statements">labeled</a>)
  4160. <a href="#Fallthrough_statements">"fallthrough" statement</a> to
  4161. indicate that control should flow from the end of this clause to
  4162. the first statement of the next clause.
  4163. Otherwise control flows to the end of the "switch" statement.
  4164. A "fallthrough" statement may appear as the last statement of all
  4165. but the last clause of an expression switch.
  4166. </p>
  4167. <p>
  4168. The switch expression may be preceded by a simple statement, which
  4169. executes before the expression is evaluated.
  4170. </p>
  4171. <pre>
  4172. switch tag {
  4173. default: s3()
  4174. case 0, 1, 2, 3: s1()
  4175. case 4, 5, 6, 7: s2()
  4176. }
  4177. switch x := f(); { // missing switch expression means "true"
  4178. case x &lt; 0: return -x
  4179. default: return x
  4180. }
  4181. switch {
  4182. case x &lt; y: f1()
  4183. case x &lt; z: f2()
  4184. case x == 4: f3()
  4185. }
  4186. </pre>
  4187. <p>
  4188. Implementation restriction: A compiler may disallow multiple case
  4189. expressions evaluating to the same constant.
  4190. For instance, the current compilers disallow duplicate integer,
  4191. floating point, or string constants in case expressions.
  4192. </p>
  4193. <h4 id="Type_switches">Type switches</h4>
  4194. <p>
  4195. A type switch compares types rather than values. It is otherwise similar
  4196. to an expression switch. It is marked by a special switch expression that
  4197. has the form of a <a href="#Type_assertions">type assertion</a>
  4198. using the keyword <code>type</code> rather than an actual type:
  4199. </p>
  4200. <pre>
  4201. switch x.(type) {
  4202. // cases
  4203. }
  4204. </pre>
  4205. <p>
  4206. Cases then match actual types <code>T</code> against the dynamic type of the
  4207. expression <code>x</code>. As with type assertions, <code>x</code> must be of
  4208. <a href="#Interface_types">interface type</a>, and each non-interface type
  4209. <code>T</code> listed in a case must implement the type of <code>x</code>.
  4210. The types listed in the cases of a type switch must all be
  4211. <a href="#Type_identity">different</a>.
  4212. </p>
  4213. <pre class="ebnf">
  4214. TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
  4215. TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
  4216. TypeCaseClause = TypeSwitchCase ":" StatementList .
  4217. TypeSwitchCase = "case" TypeList | "default" .
  4218. TypeList = Type { "," Type } .
  4219. </pre>
  4220. <p>
  4221. The TypeSwitchGuard may include a
  4222. <a href="#Short_variable_declarations">short variable declaration</a>.
  4223. When that form is used, the variable is declared at the end of the
  4224. TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause.
  4225. In clauses with a case listing exactly one type, the variable
  4226. has that type; otherwise, the variable has the type of the expression
  4227. in the TypeSwitchGuard.
  4228. </p>
  4229. <p>
  4230. Instead of a type, a case may use the predeclared identifier
  4231. <a href="#Predeclared_identifiers"><code>nil</code></a>;
  4232. that case is selected when the expression in the TypeSwitchGuard
  4233. is a <code>nil</code> interface value.
  4234. There may be at most one <code>nil</code> case.
  4235. </p>
  4236. <p>
  4237. Given an expression <code>x</code> of type <code>interface{}</code>,
  4238. the following type switch:
  4239. </p>
  4240. <pre>
  4241. switch i := x.(type) {
  4242. case nil:
  4243. printString("x is nil") // type of i is type of x (interface{})
  4244. case int:
  4245. printInt(i) // type of i is int
  4246. case float64:
  4247. printFloat64(i) // type of i is float64
  4248. case func(int) float64:
  4249. printFunction(i) // type of i is func(int) float64
  4250. case bool, string:
  4251. printString("type is bool or string") // type of i is type of x (interface{})
  4252. default:
  4253. printString("don't know the type") // type of i is type of x (interface{})
  4254. }
  4255. </pre>
  4256. <p>
  4257. could be rewritten:
  4258. </p>
  4259. <pre>
  4260. v := x // x is evaluated exactly once
  4261. if v == nil {
  4262. i := v // type of i is type of x (interface{})
  4263. printString("x is nil")
  4264. } else if i, isInt := v.(int); isInt {
  4265. printInt(i) // type of i is int
  4266. } else if i, isFloat64 := v.(float64); isFloat64 {
  4267. printFloat64(i) // type of i is float64
  4268. } else if i, isFunc := v.(func(int) float64); isFunc {
  4269. printFunction(i) // type of i is func(int) float64
  4270. } else {
  4271. _, isBool := v.(bool)
  4272. _, isString := v.(string)
  4273. if isBool || isString {
  4274. i := v // type of i is type of x (interface{})
  4275. printString("type is bool or string")
  4276. } else {
  4277. i := v // type of i is type of x (interface{})
  4278. printString("don't know the type")
  4279. }
  4280. }
  4281. </pre>
  4282. <p>
  4283. The type switch guard may be preceded by a simple statement, which
  4284. executes before the guard is evaluated.
  4285. </p>
  4286. <p>
  4287. The "fallthrough" statement is not permitted in a type switch.
  4288. </p>
  4289. <h3 id="For_statements">For statements</h3>
  4290. <p>
  4291. A "for" statement specifies repeated execution of a block. There are three forms:
  4292. The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.
  4293. </p>
  4294. <pre class="ebnf">
  4295. ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
  4296. Condition = Expression .
  4297. </pre>
  4298. <h4 id="For_condition">For statements with single condition</h4>
  4299. <p>
  4300. In its simplest form, a "for" statement specifies the repeated execution of
  4301. a block as long as a boolean condition evaluates to true.
  4302. The condition is evaluated before each iteration.
  4303. If the condition is absent, it is equivalent to the boolean value
  4304. <code>true</code>.
  4305. </p>
  4306. <pre>
  4307. for a &lt; b {
  4308. a *= 2
  4309. }
  4310. </pre>
  4311. <h4 id="For_clause">For statements with <code>for</code> clause</h4>
  4312. <p>
  4313. A "for" statement with a ForClause is also controlled by its condition, but
  4314. additionally it may specify an <i>init</i>
  4315. and a <i>post</i> statement, such as an assignment,
  4316. an increment or decrement statement. The init statement may be a
  4317. <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
  4318. Variables declared by the init statement are re-used in each iteration.
  4319. </p>
  4320. <pre class="ebnf">
  4321. ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
  4322. InitStmt = SimpleStmt .
  4323. PostStmt = SimpleStmt .
  4324. </pre>
  4325. <pre>
  4326. for i := 0; i &lt; 10; i++ {
  4327. f(i)
  4328. }
  4329. </pre>
  4330. <p>
  4331. If non-empty, the init statement is executed once before evaluating the
  4332. condition for the first iteration;
  4333. the post statement is executed after each execution of the block (and
  4334. only if the block was executed).
  4335. Any element of the ForClause may be empty but the
  4336. <a href="#Semicolons">semicolons</a> are
  4337. required unless there is only a condition.
  4338. If the condition is absent, it is equivalent to the boolean value
  4339. <code>true</code>.
  4340. </p>
  4341. <pre>
  4342. for cond { S() } is the same as for ; cond ; { S() }
  4343. for { S() } is the same as for true { S() }
  4344. </pre>
  4345. <h4 id="For_range">For statements with <code>range</code> clause</h4>
  4346. <p>
  4347. A "for" statement with a "range" clause
  4348. iterates through all entries of an array, slice, string or map,
  4349. or values received on a channel. For each entry it assigns <i>iteration values</i>
  4350. to corresponding <i>iteration variables</i> if present and then executes the block.
  4351. </p>
  4352. <pre class="ebnf">
  4353. RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
  4354. </pre>
  4355. <p>
  4356. The expression on the right in the "range" clause is called the <i>range expression</i>,
  4357. which may be an array, pointer to an array, slice, string, map, or channel permitting
  4358. <a href="#Receive_operator">receive operations</a>.
  4359. As with an assignment, if present the operands on the left must be
  4360. <a href="#Address_operators">addressable</a> or map index expressions; they
  4361. denote the iteration variables. If the range expression is a channel, at most
  4362. one iteration variable is permitted, otherwise there may be up to two.
  4363. If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
  4364. the range clause is equivalent to the same clause without that identifier.
  4365. </p>
  4366. <p>
  4367. The range expression <code>x</code> is evaluated once before beginning the loop,
  4368. with one exception: if at most one iteration variable is present and
  4369. <code>len(x)</code> is <a href="#Length_and_capacity">constant</a>,
  4370. the range expression is not evaluated.
  4371. </p>
  4372. <p>
  4373. Function calls on the left are evaluated once per iteration.
  4374. For each iteration, iteration values are produced as follows
  4375. if the respective iteration variables are present:
  4376. </p>
  4377. <pre class="grammar">
  4378. Range expression 1st value 2nd value
  4379. array or slice a [n]E, *[n]E, or []E index i int a[i] E
  4380. string s string type index i int see below rune
  4381. map m map[K]V key k K m[k] V
  4382. channel c chan E, &lt;-chan E element e E
  4383. </pre>
  4384. <ol>
  4385. <li>
  4386. For an array, pointer to array, or slice value <code>a</code>, the index iteration
  4387. values are produced in increasing order, starting at element index 0.
  4388. If at most one iteration variable is present, the range loop produces
  4389. iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
  4390. or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
  4391. </li>
  4392. <li>
  4393. For a string value, the "range" clause iterates over the Unicode code points
  4394. in the string starting at byte index 0. On successive iterations, the index value will be the
  4395. index of the first byte of successive UTF-8-encoded code points in the string,
  4396. and the second value, of type <code>rune</code>, will be the value of
  4397. the corresponding code point. If the iteration encounters an invalid
  4398. UTF-8 sequence, the second value will be <code>0xFFFD</code>,
  4399. the Unicode replacement character, and the next iteration will advance
  4400. a single byte in the string.
  4401. </li>
  4402. <li>
  4403. The iteration order over maps is not specified
  4404. and is not guaranteed to be the same from one iteration to the next.
  4405. If a map entry that has not yet been reached is removed during iteration,
  4406. the corresponding iteration value will not be produced. If a map entry is
  4407. created during iteration, that entry may be produced during the iteration or
  4408. may be skipped. The choice may vary for each entry created and from one
  4409. iteration to the next.
  4410. If the map is <code>nil</code>, the number of iterations is 0.
  4411. </li>
  4412. <li>
  4413. For channels, the iteration values produced are the successive values sent on
  4414. the channel until the channel is <a href="#Close">closed</a>. If the channel
  4415. is <code>nil</code>, the range expression blocks forever.
  4416. </li>
  4417. </ol>
  4418. <p>
  4419. The iteration values are assigned to the respective
  4420. iteration variables as in an <a href="#Assignments">assignment statement</a>.
  4421. </p>
  4422. <p>
  4423. The iteration variables may be declared by the "range" clause using a form of
  4424. <a href="#Short_variable_declarations">short variable declaration</a>
  4425. (<code>:=</code>).
  4426. In this case their types are set to the types of the respective iteration values
  4427. and their <a href="#Declarations_and_scope">scope</a> is the block of the "for"
  4428. statement; they are re-used in each iteration.
  4429. If the iteration variables are declared outside the "for" statement,
  4430. after execution their values will be those of the last iteration.
  4431. </p>
  4432. <pre>
  4433. var testdata *struct {
  4434. a *[7]int
  4435. }
  4436. for i, _ := range testdata.a {
  4437. // testdata.a is never evaluated; len(testdata.a) is constant
  4438. // i ranges from 0 to 6
  4439. f(i)
  4440. }
  4441. var a [10]string
  4442. for i, s := range a {
  4443. // type of i is int
  4444. // type of s is string
  4445. // s == a[i]
  4446. g(i, s)
  4447. }
  4448. var key string
  4449. var val interface{} // element type of m is assignable to val
  4450. m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
  4451. for key, val = range m {
  4452. h(key, val)
  4453. }
  4454. // key == last map key encountered in iteration
  4455. // val == map[key]
  4456. var ch chan Work = producer()
  4457. for w := range ch {
  4458. doWork(w)
  4459. }
  4460. // empty a channel
  4461. for range ch {}
  4462. </pre>
  4463. <h3 id="Go_statements">Go statements</h3>
  4464. <p>
  4465. A "go" statement starts the execution of a function call
  4466. as an independent concurrent thread of control, or <i>goroutine</i>,
  4467. within the same address space.
  4468. </p>
  4469. <pre class="ebnf">
  4470. GoStmt = "go" Expression .
  4471. </pre>
  4472. <p>
  4473. The expression must be a function or method call; it cannot be parenthesized.
  4474. Calls of built-in functions are restricted as for
  4475. <a href="#Expression_statements">expression statements</a>.
  4476. </p>
  4477. <p>
  4478. The function value and parameters are
  4479. <a href="#Calls">evaluated as usual</a>
  4480. in the calling goroutine, but
  4481. unlike with a regular call, program execution does not wait
  4482. for the invoked function to complete.
  4483. Instead, the function begins executing independently
  4484. in a new goroutine.
  4485. When the function terminates, its goroutine also terminates.
  4486. If the function has any return values, they are discarded when the
  4487. function completes.
  4488. </p>
  4489. <pre>
  4490. go Server()
  4491. go func(ch chan&lt;- bool) { for { sleep(10); ch &lt;- true }} (c)
  4492. </pre>
  4493. <h3 id="Select_statements">Select statements</h3>
  4494. <p>
  4495. A "select" statement chooses which of a set of possible
  4496. <a href="#Send_statements">send</a> or
  4497. <a href="#Receive_operator">receive</a>
  4498. operations will proceed.
  4499. It looks similar to a
  4500. <a href="#Switch_statements">"switch"</a> statement but with the
  4501. cases all referring to communication operations.
  4502. </p>
  4503. <pre class="ebnf">
  4504. SelectStmt = "select" "{" { CommClause } "}" .
  4505. CommClause = CommCase ":" StatementList .
  4506. CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
  4507. RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
  4508. RecvExpr = Expression .
  4509. </pre>
  4510. <p>
  4511. A case with a RecvStmt may assign the result of a RecvExpr to one or
  4512. two variables, which may be declared using a
  4513. <a href="#Short_variable_declarations">short variable declaration</a>.
  4514. The RecvExpr must be a (possibly parenthesized) receive operation.
  4515. There can be at most one default case and it may appear anywhere
  4516. in the list of cases.
  4517. </p>
  4518. <p>
  4519. Execution of a "select" statement proceeds in several steps:
  4520. </p>
  4521. <ol>
  4522. <li>
  4523. For all the cases in the statement, the channel operands of receive operations
  4524. and the channel and right-hand-side expressions of send statements are
  4525. evaluated exactly once, in source order, upon entering the "select" statement.
  4526. The result is a set of channels to receive from or send to,
  4527. and the corresponding values to send.
  4528. Any side effects in that evaluation will occur irrespective of which (if any)
  4529. communication operation is selected to proceed.
  4530. Expressions on the left-hand side of a RecvStmt with a short variable declaration
  4531. or assignment are not yet evaluated.
  4532. </li>
  4533. <li>
  4534. If one or more of the communications can proceed,
  4535. a single one that can proceed is chosen via a uniform pseudo-random selection.
  4536. Otherwise, if there is a default case, that case is chosen.
  4537. If there is no default case, the "select" statement blocks until
  4538. at least one of the communications can proceed.
  4539. </li>
  4540. <li>
  4541. Unless the selected case is the default case, the respective communication
  4542. operation is executed.
  4543. </li>
  4544. <li>
  4545. If the selected case is a RecvStmt with a short variable declaration or
  4546. an assignment, the left-hand side expressions are evaluated and the
  4547. received value (or values) are assigned.
  4548. </li>
  4549. <li>
  4550. The statement list of the selected case is executed.
  4551. </li>
  4552. </ol>
  4553. <p>
  4554. Since communication on <code>nil</code> channels can never proceed,
  4555. a select with only <code>nil</code> channels and no default case blocks forever.
  4556. </p>
  4557. <pre>
  4558. var a []int
  4559. var c, c1, c2, c3, c4 chan int
  4560. var i1, i2 int
  4561. select {
  4562. case i1 = &lt;-c1:
  4563. print("received ", i1, " from c1\n")
  4564. case c2 &lt;- i2:
  4565. print("sent ", i2, " to c2\n")
  4566. case i3, ok := (&lt;-c3): // same as: i3, ok := &lt;-c3
  4567. if ok {
  4568. print("received ", i3, " from c3\n")
  4569. } else {
  4570. print("c3 is closed\n")
  4571. }
  4572. case a[f()] = &lt;-c4:
  4573. // same as:
  4574. // case t := &lt;-c4
  4575. // a[f()] = t
  4576. default:
  4577. print("no communication\n")
  4578. }
  4579. for { // send random sequence of bits to c
  4580. select {
  4581. case c &lt;- 0: // note: no statement, no fallthrough, no folding of cases
  4582. case c &lt;- 1:
  4583. }
  4584. }
  4585. select {} // block forever
  4586. </pre>
  4587. <h3 id="Return_statements">Return statements</h3>
  4588. <p>
  4589. A "return" statement in a function <code>F</code> terminates the execution
  4590. of <code>F</code>, and optionally provides one or more result values.
  4591. Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
  4592. are executed before <code>F</code> returns to its caller.
  4593. </p>
  4594. <pre class="ebnf">
  4595. ReturnStmt = "return" [ ExpressionList ] .
  4596. </pre>
  4597. <p>
  4598. In a function without a result type, a "return" statement must not
  4599. specify any result values.
  4600. </p>
  4601. <pre>
  4602. func noResult() {
  4603. return
  4604. }
  4605. </pre>
  4606. <p>
  4607. There are three ways to return values from a function with a result
  4608. type:
  4609. </p>
  4610. <ol>
  4611. <li>The return value or values may be explicitly listed
  4612. in the "return" statement. Each expression must be single-valued
  4613. and <a href="#Assignability">assignable</a>
  4614. to the corresponding element of the function's result type.
  4615. <pre>
  4616. func simpleF() int {
  4617. return 2
  4618. }
  4619. func complexF1() (re float64, im float64) {
  4620. return -7.0, -4.0
  4621. }
  4622. </pre>
  4623. </li>
  4624. <li>The expression list in the "return" statement may be a single
  4625. call to a multi-valued function. The effect is as if each value
  4626. returned from that function were assigned to a temporary
  4627. variable with the type of the respective value, followed by a
  4628. "return" statement listing these variables, at which point the
  4629. rules of the previous case apply.
  4630. <pre>
  4631. func complexF2() (re float64, im float64) {
  4632. return complexF1()
  4633. }
  4634. </pre>
  4635. </li>
  4636. <li>The expression list may be empty if the function's result
  4637. type specifies names for its <a href="#Function_types">result parameters</a>.
  4638. The result parameters act as ordinary local variables
  4639. and the function may assign values to them as necessary.
  4640. The "return" statement returns the values of these variables.
  4641. <pre>
  4642. func complexF3() (re float64, im float64) {
  4643. re = 7.0
  4644. im = 4.0
  4645. return
  4646. }
  4647. func (devnull) Write(p []byte) (n int, _ error) {
  4648. n = len(p)
  4649. return
  4650. }
  4651. </pre>
  4652. </li>
  4653. </ol>
  4654. <p>
  4655. Regardless of how they are declared, all the result values are initialized to
  4656. the <a href="#The_zero_value">zero values</a> for their type upon entry to the
  4657. function. A "return" statement that specifies results sets the result parameters before
  4658. any deferred functions are executed.
  4659. </p>
  4660. <p>
  4661. Implementation restriction: A compiler may disallow an empty expression list
  4662. in a "return" statement if a different entity (constant, type, or variable)
  4663. with the same name as a result parameter is in
  4664. <a href="#Declarations_and_scope">scope</a> at the place of the return.
  4665. </p>
  4666. <pre>
  4667. func f(n int) (res int, err error) {
  4668. if _, err := f(n-1); err != nil {
  4669. return // invalid return statement: err is shadowed
  4670. }
  4671. return
  4672. }
  4673. </pre>
  4674. <h3 id="Break_statements">Break statements</h3>
  4675. <p>
  4676. A "break" statement terminates execution of the innermost
  4677. <a href="#For_statements">"for"</a>,
  4678. <a href="#Switch_statements">"switch"</a>, or
  4679. <a href="#Select_statements">"select"</a> statement
  4680. within the same function.
  4681. </p>
  4682. <pre class="ebnf">
  4683. BreakStmt = "break" [ Label ] .
  4684. </pre>
  4685. <p>
  4686. If there is a label, it must be that of an enclosing
  4687. "for", "switch", or "select" statement,
  4688. and that is the one whose execution terminates.
  4689. </p>
  4690. <pre>
  4691. OuterLoop:
  4692. for i = 0; i &lt; n; i++ {
  4693. for j = 0; j &lt; m; j++ {
  4694. switch a[i][j] {
  4695. case nil:
  4696. state = Error
  4697. break OuterLoop
  4698. case item:
  4699. state = Found
  4700. break OuterLoop
  4701. }
  4702. }
  4703. }
  4704. </pre>
  4705. <h3 id="Continue_statements">Continue statements</h3>
  4706. <p>
  4707. A "continue" statement begins the next iteration of the
  4708. innermost <a href="#For_statements">"for" loop</a> at its post statement.
  4709. The "for" loop must be within the same function.
  4710. </p>
  4711. <pre class="ebnf">
  4712. ContinueStmt = "continue" [ Label ] .
  4713. </pre>
  4714. <p>
  4715. If there is a label, it must be that of an enclosing
  4716. "for" statement, and that is the one whose execution
  4717. advances.
  4718. </p>
  4719. <pre>
  4720. RowLoop:
  4721. for y, row := range rows {
  4722. for x, data := range row {
  4723. if data == endOfRow {
  4724. continue RowLoop
  4725. }
  4726. row[x] = data + bias(x, y)
  4727. }
  4728. }
  4729. </pre>
  4730. <h3 id="Goto_statements">Goto statements</h3>
  4731. <p>
  4732. A "goto" statement transfers control to the statement with the corresponding label
  4733. within the same function.
  4734. </p>
  4735. <pre class="ebnf">
  4736. GotoStmt = "goto" Label .
  4737. </pre>
  4738. <pre>
  4739. goto Error
  4740. </pre>
  4741. <p>
  4742. Executing the "goto" statement must not cause any variables to come into
  4743. <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
  4744. For instance, this example:
  4745. </p>
  4746. <pre>
  4747. goto L // BAD
  4748. v := 3
  4749. L:
  4750. </pre>
  4751. <p>
  4752. is erroneous because the jump to label <code>L</code> skips
  4753. the creation of <code>v</code>.
  4754. </p>
  4755. <p>
  4756. A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
  4757. For instance, this example:
  4758. </p>
  4759. <pre>
  4760. if n%2 == 1 {
  4761. goto L1
  4762. }
  4763. for n &gt; 0 {
  4764. f()
  4765. n--
  4766. L1:
  4767. f()
  4768. n--
  4769. }
  4770. </pre>
  4771. <p>
  4772. is erroneous because the label <code>L1</code> is inside
  4773. the "for" statement's block but the <code>goto</code> is not.
  4774. </p>
  4775. <h3 id="Fallthrough_statements">Fallthrough statements</h3>
  4776. <p>
  4777. A "fallthrough" statement transfers control to the first statement of the
  4778. next case clause in an <a href="#Expression_switches">expression "switch" statement</a>.
  4779. It may be used only as the final non-empty statement in such a clause.
  4780. </p>
  4781. <pre class="ebnf">
  4782. FallthroughStmt = "fallthrough" .
  4783. </pre>
  4784. <h3 id="Defer_statements">Defer statements</h3>
  4785. <p>
  4786. A "defer" statement invokes a function whose execution is deferred
  4787. to the moment the surrounding function returns, either because the
  4788. surrounding function executed a <a href="#Return_statements">return statement</a>,
  4789. reached the end of its <a href="#Function_declarations">function body</a>,
  4790. or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
  4791. </p>
  4792. <pre class="ebnf">
  4793. DeferStmt = "defer" Expression .
  4794. </pre>
  4795. <p>
  4796. The expression must be a function or method call; it cannot be parenthesized.
  4797. Calls of built-in functions are restricted as for
  4798. <a href="#Expression_statements">expression statements</a>.
  4799. </p>
  4800. <p>
  4801. Each time a "defer" statement
  4802. executes, the function value and parameters to the call are
  4803. <a href="#Calls">evaluated as usual</a>
  4804. and saved anew but the actual function is not invoked.
  4805. Instead, deferred functions are invoked immediately before
  4806. the surrounding function returns, in the reverse order
  4807. they were deferred. That is, if the surrounding function
  4808. returns through an explicit <a href="#Return_statements">return statement</a>,
  4809. deferred functions are executed <i>after</i> any result parameters are set
  4810. by that return statement but <i>before</i> the function returns to its caller.
  4811. If a deferred function value evaluates
  4812. to <code>nil</code>, execution <a href="#Handling_panics">panics</a>
  4813. when the function is invoked, not when the "defer" statement is executed.
  4814. </p>
  4815. <p>
  4816. For instance, if the deferred function is
  4817. a <a href="#Function_literals">function literal</a> and the surrounding
  4818. function has <a href="#Function_types">named result parameters</a> that
  4819. are in scope within the literal, the deferred function may access and modify
  4820. the result parameters before they are returned.
  4821. If the deferred function has any return values, they are discarded when
  4822. the function completes.
  4823. (See also the section on <a href="#Handling_panics">handling panics</a>.)
  4824. </p>
  4825. <pre>
  4826. lock(l)
  4827. defer unlock(l) // unlocking happens before surrounding function returns
  4828. // prints 3 2 1 0 before surrounding function returns
  4829. for i := 0; i &lt;= 3; i++ {
  4830. defer fmt.Print(i)
  4831. }
  4832. // f returns 42
  4833. func f() (result int) {
  4834. defer func() {
  4835. // result is accessed after it was set to 6 by the return statement
  4836. result *= 7
  4837. }()
  4838. return 6
  4839. }
  4840. </pre>
  4841. <h2 id="Built-in_functions">Built-in functions</h2>
  4842. <p>
  4843. Built-in functions are
  4844. <a href="#Predeclared_identifiers">predeclared</a>.
  4845. They are called like any other function but some of them
  4846. accept a type instead of an expression as the first argument.
  4847. </p>
  4848. <p>
  4849. The built-in functions do not have standard Go types,
  4850. so they can only appear in <a href="#Calls">call expressions</a>;
  4851. they cannot be used as function values.
  4852. </p>
  4853. <h3 id="Close">Close</h3>
  4854. <p>
  4855. For a channel <code>c</code>, the built-in function <code>close(c)</code>
  4856. records that no more values will be sent on the channel.
  4857. It is an error if <code>c</code> is a receive-only channel.
  4858. Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
  4859. Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
  4860. After calling <code>close</code>, and after any previously
  4861. sent values have been received, receive operations will return
  4862. the zero value for the channel's type without blocking.
  4863. The multi-valued <a href="#Receive_operator">receive operation</a>
  4864. returns a received value along with an indication of whether the channel is closed.
  4865. </p>
  4866. <h3 id="Length_and_capacity">Length and capacity</h3>
  4867. <p>
  4868. The built-in functions <code>len</code> and <code>cap</code> take arguments
  4869. of various types and return a result of type <code>int</code>.
  4870. The implementation guarantees that the result always fits into an <code>int</code>.
  4871. </p>
  4872. <pre class="grammar">
  4873. Call Argument type Result
  4874. len(s) string type string length in bytes
  4875. [n]T, *[n]T array length (== n)
  4876. []T slice length
  4877. map[K]T map length (number of defined keys)
  4878. chan T number of elements queued in channel buffer
  4879. cap(s) [n]T, *[n]T array length (== n)
  4880. []T slice capacity
  4881. chan T channel buffer capacity
  4882. </pre>
  4883. <p>
  4884. The capacity of a slice is the number of elements for which there is
  4885. space allocated in the underlying array.
  4886. At any time the following relationship holds:
  4887. </p>
  4888. <pre>
  4889. 0 &lt;= len(s) &lt;= cap(s)
  4890. </pre>
  4891. <p>
  4892. The length of a <code>nil</code> slice, map or channel is 0.
  4893. The capacity of a <code>nil</code> slice or channel is 0.
  4894. </p>
  4895. <p>
  4896. The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
  4897. <code>s</code> is a string constant. The expressions <code>len(s)</code> and
  4898. <code>cap(s)</code> are constants if the type of <code>s</code> is an array
  4899. or pointer to an array and the expression <code>s</code> does not contain
  4900. <a href="#Receive_operator">channel receives</a> or (non-constant)
  4901. <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
  4902. Otherwise, invocations of <code>len</code> and <code>cap</code> are not
  4903. constant and <code>s</code> is evaluated.
  4904. </p>
  4905. <pre>
  4906. const (
  4907. c1 = imag(2i) // imag(2i) = 2.0 is a constant
  4908. c2 = len([10]float64{2}) // [10]float64{2} contains no function calls
  4909. c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls
  4910. c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued
  4911. c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call
  4912. )
  4913. var z complex128
  4914. </pre>
  4915. <h3 id="Allocation">Allocation</h3>
  4916. <p>
  4917. The built-in function <code>new</code> takes a type <code>T</code>,
  4918. allocates storage for a <a href="#Variables">variable</a> of that type
  4919. at run time, and returns a value of type <code>*T</code>
  4920. <a href="#Pointer_types">pointing</a> to it.
  4921. The variable is initialized as described in the section on
  4922. <a href="#The_zero_value">initial values</a>.
  4923. </p>
  4924. <pre class="grammar">
  4925. new(T)
  4926. </pre>
  4927. <p>
  4928. For instance
  4929. </p>
  4930. <pre>
  4931. type S struct { a int; b float64 }
  4932. new(S)
  4933. </pre>
  4934. <p>
  4935. allocates storage for a variable of type <code>S</code>,
  4936. initializes it (<code>a=0</code>, <code>b=0.0</code>),
  4937. and returns a value of type <code>*S</code> containing the address
  4938. of the location.
  4939. </p>
  4940. <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
  4941. <p>
  4942. The built-in function <code>make</code> takes a type <code>T</code>,
  4943. which must be a slice, map or channel type,
  4944. optionally followed by a type-specific list of expressions.
  4945. It returns a value of type <code>T</code> (not <code>*T</code>).
  4946. The memory is initialized as described in the section on
  4947. <a href="#The_zero_value">initial values</a>.
  4948. </p>
  4949. <pre class="grammar">
  4950. Call Type T Result
  4951. make(T, n) slice slice of type T with length n and capacity n
  4952. make(T, n, m) slice slice of type T with length n and capacity m
  4953. make(T) map map of type T
  4954. make(T, n) map map of type T with initial space for approximately n elements
  4955. make(T) channel unbuffered channel of type T
  4956. make(T, n) channel buffered channel of type T, buffer size n
  4957. </pre>
  4958. <p>
  4959. Each of the size arguments <code>n</code> and <code>m</code> must be of integer type
  4960. or an untyped <a href="#Constants">constant</a>.
  4961. A constant size argument must be non-negative and <a href="#Representability">representable</a>
  4962. by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>.
  4963. If both <code>n</code> and <code>m</code> are provided and are constant, then
  4964. <code>n</code> must be no larger than <code>m</code>.
  4965. If <code>n</code> is negative or larger than <code>m</code> at run time,
  4966. a <a href="#Run_time_panics">run-time panic</a> occurs.
  4967. </p>
  4968. <pre>
  4969. s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
  4970. s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
  4971. s := make([]int, 1&lt;&lt;63) // illegal: len(s) is not representable by a value of type int
  4972. s := make([]int, 10, 0) // illegal: len(s) > cap(s)
  4973. c := make(chan int, 10) // channel with a buffer size of 10
  4974. m := make(map[string]int, 100) // map with initial space for approximately 100 elements
  4975. </pre>
  4976. <p>
  4977. Calling <code>make</code> with a map type and size hint <code>n</code> will
  4978. create a map with initial space to hold <code>n</code> map elements.
  4979. The precise behavior is implementation-dependent.
  4980. </p>
  4981. <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
  4982. <p>
  4983. The built-in functions <code>append</code> and <code>copy</code> assist in
  4984. common slice operations.
  4985. For both functions, the result is independent of whether the memory referenced
  4986. by the arguments overlaps.
  4987. </p>
  4988. <p>
  4989. The <a href="#Function_types">variadic</a> function <code>append</code>
  4990. appends zero or more values <code>x</code>
  4991. to <code>s</code> of type <code>S</code>, which must be a slice type, and
  4992. returns the resulting slice, also of type <code>S</code>.
  4993. The values <code>x</code> are passed to a parameter of type <code>...T</code>
  4994. where <code>T</code> is the <a href="#Slice_types">element type</a> of
  4995. <code>S</code> and the respective
  4996. <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
  4997. As a special case, <code>append</code> also accepts a first argument
  4998. assignable to type <code>[]byte</code> with a second argument of
  4999. string type followed by <code>...</code>. This form appends the
  5000. bytes of the string.
  5001. </p>
  5002. <pre class="grammar">
  5003. append(s S, x ...T) S // T is the element type of S
  5004. </pre>
  5005. <p>
  5006. If the capacity of <code>s</code> is not large enough to fit the additional
  5007. values, <code>append</code> allocates a new, sufficiently large underlying
  5008. array that fits both the existing slice elements and the additional values.
  5009. Otherwise, <code>append</code> re-uses the underlying array.
  5010. </p>
  5011. <pre>
  5012. s0 := []int{0, 0}
  5013. s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
  5014. s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
  5015. s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
  5016. s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
  5017. var t []interface{}
  5018. t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"}
  5019. var b []byte
  5020. b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
  5021. </pre>
  5022. <p>
  5023. The function <code>copy</code> copies slice elements from
  5024. a source <code>src</code> to a destination <code>dst</code> and returns the
  5025. number of elements copied.
  5026. Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
  5027. <a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
  5028. The number of elements copied is the minimum of
  5029. <code>len(src)</code> and <code>len(dst)</code>.
  5030. As a special case, <code>copy</code> also accepts a destination argument assignable
  5031. to type <code>[]byte</code> with a source argument of a string type.
  5032. This form copies the bytes from the string into the byte slice.
  5033. </p>
  5034. <pre class="grammar">
  5035. copy(dst, src []T) int
  5036. copy(dst []byte, src string) int
  5037. </pre>
  5038. <p>
  5039. Examples:
  5040. </p>
  5041. <pre>
  5042. var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
  5043. var s = make([]int, 6)
  5044. var b = make([]byte, 5)
  5045. n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
  5046. n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
  5047. n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello")
  5048. </pre>
  5049. <h3 id="Deletion_of_map_elements">Deletion of map elements</h3>
  5050. <p>
  5051. The built-in function <code>delete</code> removes the element with key
  5052. <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
  5053. type of <code>k</code> must be <a href="#Assignability">assignable</a>
  5054. to the key type of <code>m</code>.
  5055. </p>
  5056. <pre class="grammar">
  5057. delete(m, k) // remove element m[k] from map m
  5058. </pre>
  5059. <p>
  5060. If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
  5061. does not exist, <code>delete</code> is a no-op.
  5062. </p>
  5063. <h3 id="Complex_numbers">Manipulating complex numbers</h3>
  5064. <p>
  5065. Three functions assemble and disassemble complex numbers.
  5066. The built-in function <code>complex</code> constructs a complex
  5067. value from a floating-point real and imaginary part, while
  5068. <code>real</code> and <code>imag</code>
  5069. extract the real and imaginary parts of a complex value.
  5070. </p>
  5071. <pre class="grammar">
  5072. complex(realPart, imaginaryPart floatT) complexT
  5073. real(complexT) floatT
  5074. imag(complexT) floatT
  5075. </pre>
  5076. <p>
  5077. The type of the arguments and return value correspond.
  5078. For <code>complex</code>, the two arguments must be of the same
  5079. floating-point type and the return type is the complex type
  5080. with the corresponding floating-point constituents:
  5081. <code>complex64</code> for <code>float32</code> arguments, and
  5082. <code>complex128</code> for <code>float64</code> arguments.
  5083. If one of the arguments evaluates to an untyped constant, it is first implicitly
  5084. <a href="#Conversions">converted</a> to the type of the other argument.
  5085. If both arguments evaluate to untyped constants, they must be non-complex
  5086. numbers or their imaginary parts must be zero, and the return value of
  5087. the function is an untyped complex constant.
  5088. </p>
  5089. <p>
  5090. For <code>real</code> and <code>imag</code>, the argument must be
  5091. of complex type, and the return type is the corresponding floating-point
  5092. type: <code>float32</code> for a <code>complex64</code> argument, and
  5093. <code>float64</code> for a <code>complex128</code> argument.
  5094. If the argument evaluates to an untyped constant, it must be a number,
  5095. and the return value of the function is an untyped floating-point constant.
  5096. </p>
  5097. <p>
  5098. The <code>real</code> and <code>imag</code> functions together form the inverse of
  5099. <code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>,
  5100. <code>z&nbsp;==&nbsp;Z(complex(real(z),&nbsp;imag(z)))</code>.
  5101. </p>
  5102. <p>
  5103. If the operands of these functions are all constants, the return
  5104. value is a constant.
  5105. </p>
  5106. <pre>
  5107. var a = complex(2, -2) // complex128
  5108. const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i
  5109. x := float32(math.Cos(math.Pi/2)) // float32
  5110. var c64 = complex(5, -x) // complex64
  5111. var s int = complex(1, 0) // untyped complex constant 1 + 0i can be converted to int
  5112. _ = complex(1, 2&lt;&lt;s) // illegal: 2 assumes floating-point type, cannot shift
  5113. var rl = real(c64) // float32
  5114. var im = imag(a) // float64
  5115. const c = imag(b) // untyped constant -1.4
  5116. _ = imag(3 &lt;&lt; s) // illegal: 3 assumes complex type, cannot shift
  5117. </pre>
  5118. <h3 id="Handling_panics">Handling panics</h3>
  5119. <p> Two built-in functions, <code>panic</code> and <code>recover</code>,
  5120. assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
  5121. and program-defined error conditions.
  5122. </p>
  5123. <pre class="grammar">
  5124. func panic(interface{})
  5125. func recover() interface{}
  5126. </pre>
  5127. <p>
  5128. While executing a function <code>F</code>,
  5129. an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
  5130. terminates the execution of <code>F</code>.
  5131. Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
  5132. are then executed as usual.
  5133. Next, any deferred functions run by <code>F's</code> caller are run,
  5134. and so on up to any deferred by the top-level function in the executing goroutine.
  5135. At that point, the program is terminated and the error
  5136. condition is reported, including the value of the argument to <code>panic</code>.
  5137. This termination sequence is called <i>panicking</i>.
  5138. </p>
  5139. <pre>
  5140. panic(42)
  5141. panic("unreachable")
  5142. panic(Error("cannot parse"))
  5143. </pre>
  5144. <p>
  5145. The <code>recover</code> function allows a program to manage behavior
  5146. of a panicking goroutine.
  5147. Suppose a function <code>G</code> defers a function <code>D</code> that calls
  5148. <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
  5149. is executing.
  5150. When the running of deferred functions reaches <code>D</code>,
  5151. the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>.
  5152. If <code>D</code> returns normally, without starting a new
  5153. <code>panic</code>, the panicking sequence stops. In that case,
  5154. the state of functions called between <code>G</code> and the call to <code>panic</code>
  5155. is discarded, and normal execution resumes.
  5156. Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
  5157. execution terminates by returning to its caller.
  5158. </p>
  5159. <p>
  5160. The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
  5161. </p>
  5162. <ul>
  5163. <li>
  5164. <code>panic</code>'s argument was <code>nil</code>;
  5165. </li>
  5166. <li>
  5167. the goroutine is not panicking;
  5168. </li>
  5169. <li>
  5170. <code>recover</code> was not called directly by a deferred function.
  5171. </li>
  5172. </ul>
  5173. <p>
  5174. The <code>protect</code> function in the example below invokes
  5175. the function argument <code>g</code> and protects callers from
  5176. run-time panics raised by <code>g</code>.
  5177. </p>
  5178. <pre>
  5179. func protect(g func()) {
  5180. defer func() {
  5181. log.Println("done") // Println executes normally even if there is a panic
  5182. if x := recover(); x != nil {
  5183. log.Printf("run time panic: %v", x)
  5184. }
  5185. }()
  5186. log.Println("start")
  5187. g()
  5188. }
  5189. </pre>
  5190. <h3 id="Bootstrapping">Bootstrapping</h3>
  5191. <p>
  5192. Current implementations provide several built-in functions useful during
  5193. bootstrapping. These functions are documented for completeness but are not
  5194. guaranteed to stay in the language. They do not return a result.
  5195. </p>
  5196. <pre class="grammar">
  5197. Function Behavior
  5198. print prints all arguments; formatting of arguments is implementation-specific
  5199. println like print but prints spaces between arguments and a newline at the end
  5200. </pre>
  5201. <p>
  5202. Implementation restriction: <code>print</code> and <code>println</code> need not
  5203. accept arbitrary argument types, but printing of boolean, numeric, and string
  5204. <a href="#Types">types</a> must be supported.
  5205. </p>
  5206. <h2 id="Packages">Packages</h2>
  5207. <p>
  5208. Go programs are constructed by linking together <i>packages</i>.
  5209. A package in turn is constructed from one or more source files
  5210. that together declare constants, types, variables and functions
  5211. belonging to the package and which are accessible in all files
  5212. of the same package. Those elements may be
  5213. <a href="#Exported_identifiers">exported</a> and used in another package.
  5214. </p>
  5215. <h3 id="Source_file_organization">Source file organization</h3>
  5216. <p>
  5217. Each source file consists of a package clause defining the package
  5218. to which it belongs, followed by a possibly empty set of import
  5219. declarations that declare packages whose contents it wishes to use,
  5220. followed by a possibly empty set of declarations of functions,
  5221. types, variables, and constants.
  5222. </p>
  5223. <pre class="ebnf">
  5224. SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
  5225. </pre>
  5226. <h3 id="Package_clause">Package clause</h3>
  5227. <p>
  5228. A package clause begins each source file and defines the package
  5229. to which the file belongs.
  5230. </p>
  5231. <pre class="ebnf">
  5232. PackageClause = "package" PackageName .
  5233. PackageName = identifier .
  5234. </pre>
  5235. <p>
  5236. The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
  5237. </p>
  5238. <pre>
  5239. package math
  5240. </pre>
  5241. <p>
  5242. A set of files sharing the same PackageName form the implementation of a package.
  5243. An implementation may require that all source files for a package inhabit the same directory.
  5244. </p>
  5245. <h3 id="Import_declarations">Import declarations</h3>
  5246. <p>
  5247. An import declaration states that the source file containing the declaration
  5248. depends on functionality of the <i>imported</i> package
  5249. (<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
  5250. and enables access to <a href="#Exported_identifiers">exported</a> identifiers
  5251. of that package.
  5252. The import names an identifier (PackageName) to be used for access and an ImportPath
  5253. that specifies the package to be imported.
  5254. </p>
  5255. <pre class="ebnf">
  5256. ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
  5257. ImportSpec = [ "." | PackageName ] ImportPath .
  5258. ImportPath = string_lit .
  5259. </pre>
  5260. <p>
  5261. The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
  5262. to access exported identifiers of the package within the importing source file.
  5263. It is declared in the <a href="#Blocks">file block</a>.
  5264. If the PackageName is omitted, it defaults to the identifier specified in the
  5265. <a href="#Package_clause">package clause</a> of the imported package.
  5266. If an explicit period (<code>.</code>) appears instead of a name, all the
  5267. package's exported identifiers declared in that package's
  5268. <a href="#Blocks">package block</a> will be declared in the importing source
  5269. file's file block and must be accessed without a qualifier.
  5270. </p>
  5271. <p>
  5272. The interpretation of the ImportPath is implementation-dependent but
  5273. it is typically a substring of the full file name of the compiled
  5274. package and may be relative to a repository of installed packages.
  5275. </p>
  5276. <p>
  5277. Implementation restriction: A compiler may restrict ImportPaths to
  5278. non-empty strings using only characters belonging to
  5279. <a href="https://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
  5280. L, M, N, P, and S general categories (the Graphic characters without
  5281. spaces) and may also exclude the characters
  5282. <code>!"#$%&amp;'()*,:;&lt;=&gt;?[\]^`{|}</code>
  5283. and the Unicode replacement character U+FFFD.
  5284. </p>
  5285. <p>
  5286. Assume we have compiled a package containing the package clause
  5287. <code>package math</code>, which exports function <code>Sin</code>, and
  5288. installed the compiled package in the file identified by
  5289. <code>"lib/math"</code>.
  5290. This table illustrates how <code>Sin</code> is accessed in files
  5291. that import the package after the
  5292. various types of import declaration.
  5293. </p>
  5294. <pre class="grammar">
  5295. Import declaration Local name of Sin
  5296. import "lib/math" math.Sin
  5297. import m "lib/math" m.Sin
  5298. import . "lib/math" Sin
  5299. </pre>
  5300. <p>
  5301. An import declaration declares a dependency relation between
  5302. the importing and imported package.
  5303. It is illegal for a package to import itself, directly or indirectly,
  5304. or to directly import a package without
  5305. referring to any of its exported identifiers. To import a package solely for
  5306. its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
  5307. identifier as explicit package name:
  5308. </p>
  5309. <pre>
  5310. import _ "lib/math"
  5311. </pre>
  5312. <h3 id="An_example_package">An example package</h3>
  5313. <p>
  5314. Here is a complete Go package that implements a concurrent prime sieve.
  5315. </p>
  5316. <pre>
  5317. package main
  5318. import "fmt"
  5319. // Send the sequence 2, 3, 4, … to channel 'ch'.
  5320. func generate(ch chan&lt;- int) {
  5321. for i := 2; ; i++ {
  5322. ch &lt;- i // Send 'i' to channel 'ch'.
  5323. }
  5324. }
  5325. // Copy the values from channel 'src' to channel 'dst',
  5326. // removing those divisible by 'prime'.
  5327. func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
  5328. for i := range src { // Loop over values received from 'src'.
  5329. if i%prime != 0 {
  5330. dst &lt;- i // Send 'i' to channel 'dst'.
  5331. }
  5332. }
  5333. }
  5334. // The prime sieve: Daisy-chain filter processes together.
  5335. func sieve() {
  5336. ch := make(chan int) // Create a new channel.
  5337. go generate(ch) // Start generate() as a subprocess.
  5338. for {
  5339. prime := &lt;-ch
  5340. fmt.Print(prime, "\n")
  5341. ch1 := make(chan int)
  5342. go filter(ch, ch1, prime)
  5343. ch = ch1
  5344. }
  5345. }
  5346. func main() {
  5347. sieve()
  5348. }
  5349. </pre>
  5350. <h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
  5351. <h3 id="The_zero_value">The zero value</h3>
  5352. <p>
  5353. When storage is allocated for a <a href="#Variables">variable</a>,
  5354. either through a declaration or a call of <code>new</code>, or when
  5355. a new value is created, either through a composite literal or a call
  5356. of <code>make</code>,
  5357. and no explicit initialization is provided, the variable or value is
  5358. given a default value. Each element of such a variable or value is
  5359. set to the <i>zero value</i> for its type: <code>false</code> for booleans,
  5360. <code>0</code> for numeric types, <code>""</code>
  5361. for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
  5362. This initialization is done recursively, so for instance each element of an
  5363. array of structs will have its fields zeroed if no value is specified.
  5364. </p>
  5365. <p>
  5366. These two simple declarations are equivalent:
  5367. </p>
  5368. <pre>
  5369. var i int
  5370. var i int = 0
  5371. </pre>
  5372. <p>
  5373. After
  5374. </p>
  5375. <pre>
  5376. type T struct { i int; f float64; next *T }
  5377. t := new(T)
  5378. </pre>
  5379. <p>
  5380. the following holds:
  5381. </p>
  5382. <pre>
  5383. t.i == 0
  5384. t.f == 0.0
  5385. t.next == nil
  5386. </pre>
  5387. <p>
  5388. The same would also be true after
  5389. </p>
  5390. <pre>
  5391. var t T
  5392. </pre>
  5393. <h3 id="Package_initialization">Package initialization</h3>
  5394. <p>
  5395. Within a package, package-level variable initialization proceeds stepwise,
  5396. with each step selecting the variable earliest in <i>declaration order</i>
  5397. which has no dependencies on uninitialized variables.
  5398. </p>
  5399. <p>
  5400. More precisely, a package-level variable is considered <i>ready for
  5401. initialization</i> if it is not yet initialized and either has
  5402. no <a href="#Variable_declarations">initialization expression</a> or
  5403. its initialization expression has no <i>dependencies</i> on uninitialized variables.
  5404. Initialization proceeds by repeatedly initializing the next package-level
  5405. variable that is earliest in declaration order and ready for initialization,
  5406. until there are no variables ready for initialization.
  5407. </p>
  5408. <p>
  5409. If any variables are still uninitialized when this
  5410. process ends, those variables are part of one or more initialization cycles,
  5411. and the program is not valid.
  5412. </p>
  5413. <p>
  5414. Multiple variables on the left-hand side of a variable declaration initialized
  5415. by single (multi-valued) expression on the right-hand side are initialized
  5416. together: If any of the variables on the left-hand side is initialized, all
  5417. those variables are initialized in the same step.
  5418. </p>
  5419. <pre>
  5420. var x = a
  5421. var a, b = f() // a and b are initialized together, before x is initialized
  5422. </pre>
  5423. <p>
  5424. For the purpose of package initialization, <a href="#Blank_identifier">blank</a>
  5425. variables are treated like any other variables in declarations.
  5426. </p>
  5427. <p>
  5428. The declaration order of variables declared in multiple files is determined
  5429. by the order in which the files are presented to the compiler: Variables
  5430. declared in the first file are declared before any of the variables declared
  5431. in the second file, and so on.
  5432. </p>
  5433. <p>
  5434. Dependency analysis does not rely on the actual values of the
  5435. variables, only on lexical <i>references</i> to them in the source,
  5436. analyzed transitively. For instance, if a variable <code>x</code>'s
  5437. initialization expression refers to a function whose body refers to
  5438. variable <code>y</code> then <code>x</code> depends on <code>y</code>.
  5439. Specifically:
  5440. </p>
  5441. <ul>
  5442. <li>
  5443. A reference to a variable or function is an identifier denoting that
  5444. variable or function.
  5445. </li>
  5446. <li>
  5447. A reference to a method <code>m</code> is a
  5448. <a href="#Method_values">method value</a> or
  5449. <a href="#Method_expressions">method expression</a> of the form
  5450. <code>t.m</code>, where the (static) type of <code>t</code> is
  5451. not an interface type, and the method <code>m</code> is in the
  5452. <a href="#Method_sets">method set</a> of <code>t</code>.
  5453. It is immaterial whether the resulting function value
  5454. <code>t.m</code> is invoked.
  5455. </li>
  5456. <li>
  5457. A variable, function, or method <code>x</code> depends on a variable
  5458. <code>y</code> if <code>x</code>'s initialization expression or body
  5459. (for functions and methods) contains a reference to <code>y</code>
  5460. or to a function or method that depends on <code>y</code>.
  5461. </li>
  5462. </ul>
  5463. <p>
  5464. For example, given the declarations
  5465. </p>
  5466. <pre>
  5467. var (
  5468. a = c + b // == 9
  5469. b = f() // == 4
  5470. c = f() // == 5
  5471. d = 3 // == 5 after initialization has finished
  5472. )
  5473. func f() int {
  5474. d++
  5475. return d
  5476. }
  5477. </pre>
  5478. <p>
  5479. the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
  5480. Note that the order of subexpressions in initialization expressions is irrelevant:
  5481. <code>a = c + b</code> and <code>a = b + c</code> result in the same initialization
  5482. order in this example.
  5483. </p>
  5484. <p>
  5485. Dependency analysis is performed per package; only references referring
  5486. to variables, functions, and (non-interface) methods declared in the current
  5487. package are considered. If other, hidden, data dependencies exists between
  5488. variables, the initialization order between those variables is unspecified.
  5489. </p>
  5490. <p>
  5491. For instance, given the declarations
  5492. </p>
  5493. <pre>
  5494. var x = I(T{}).ab() // x has an undetected, hidden dependency on a and b
  5495. var _ = sideEffect() // unrelated to x, a, or b
  5496. var a = b
  5497. var b = 42
  5498. type I interface { ab() []int }
  5499. type T struct{}
  5500. func (T) ab() []int { return []int{a, b} }
  5501. </pre>
  5502. <p>
  5503. the variable <code>a</code> will be initialized after <code>b</code> but
  5504. whether <code>x</code> is initialized before <code>b</code>, between
  5505. <code>b</code> and <code>a</code>, or after <code>a</code>, and
  5506. thus also the moment at which <code>sideEffect()</code> is called (before
  5507. or after <code>x</code> is initialized) is not specified.
  5508. </p>
  5509. <p>
  5510. Variables may also be initialized using functions named <code>init</code>
  5511. declared in the package block, with no arguments and no result parameters.
  5512. </p>
  5513. <pre>
  5514. func init() { … }
  5515. </pre>
  5516. <p>
  5517. Multiple such functions may be defined per package, even within a single
  5518. source file. In the package block, the <code>init</code> identifier can
  5519. be used only to declare <code>init</code> functions, yet the identifier
  5520. itself is not <a href="#Declarations_and_scope">declared</a>. Thus
  5521. <code>init</code> functions cannot be referred to from anywhere
  5522. in a program.
  5523. </p>
  5524. <p>
  5525. A package with no imports is initialized by assigning initial values
  5526. to all its package-level variables followed by calling all <code>init</code>
  5527. functions in the order they appear in the source, possibly in multiple files,
  5528. as presented to the compiler.
  5529. If a package has imports, the imported packages are initialized
  5530. before initializing the package itself. If multiple packages import
  5531. a package, the imported package will be initialized only once.
  5532. The importing of packages, by construction, guarantees that there
  5533. can be no cyclic initialization dependencies.
  5534. </p>
  5535. <p>
  5536. Package initialization&mdash;variable initialization and the invocation of
  5537. <code>init</code> functions&mdash;happens in a single goroutine,
  5538. sequentially, one package at a time.
  5539. An <code>init</code> function may launch other goroutines, which can run
  5540. concurrently with the initialization code. However, initialization
  5541. always sequences
  5542. the <code>init</code> functions: it will not invoke the next one
  5543. until the previous one has returned.
  5544. </p>
  5545. <p>
  5546. To ensure reproducible initialization behavior, build systems are encouraged
  5547. to present multiple files belonging to the same package in lexical file name
  5548. order to a compiler.
  5549. </p>
  5550. <h3 id="Program_execution">Program execution</h3>
  5551. <p>
  5552. A complete program is created by linking a single, unimported package
  5553. called the <i>main package</i> with all the packages it imports, transitively.
  5554. The main package must
  5555. have package name <code>main</code> and
  5556. declare a function <code>main</code> that takes no
  5557. arguments and returns no value.
  5558. </p>
  5559. <pre>
  5560. func main() { … }
  5561. </pre>
  5562. <p>
  5563. Program execution begins by initializing the main package and then
  5564. invoking the function <code>main</code>.
  5565. When that function invocation returns, the program exits.
  5566. It does not wait for other (non-<code>main</code>) goroutines to complete.
  5567. </p>
  5568. <h2 id="Errors">Errors</h2>
  5569. <p>
  5570. The predeclared type <code>error</code> is defined as
  5571. </p>
  5572. <pre>
  5573. type error interface {
  5574. Error() string
  5575. }
  5576. </pre>
  5577. <p>
  5578. It is the conventional interface for representing an error condition,
  5579. with the nil value representing no error.
  5580. For instance, a function to read data from a file might be defined:
  5581. </p>
  5582. <pre>
  5583. func Read(f *File, b []byte) (n int, err error)
  5584. </pre>
  5585. <h2 id="Run_time_panics">Run-time panics</h2>
  5586. <p>
  5587. Execution errors such as attempting to index an array out
  5588. of bounds trigger a <i>run-time panic</i> equivalent to a call of
  5589. the built-in function <a href="#Handling_panics"><code>panic</code></a>
  5590. with a value of the implementation-defined interface type <code>runtime.Error</code>.
  5591. That type satisfies the predeclared interface type
  5592. <a href="#Errors"><code>error</code></a>.
  5593. The exact error values that
  5594. represent distinct run-time error conditions are unspecified.
  5595. </p>
  5596. <pre>
  5597. package runtime
  5598. type Error interface {
  5599. error
  5600. // and perhaps other methods
  5601. }
  5602. </pre>
  5603. <h2 id="System_considerations">System considerations</h2>
  5604. <h3 id="Package_unsafe">Package <code>unsafe</code></h3>
  5605. <p>
  5606. The built-in package <code>unsafe</code>, known to the compiler
  5607. and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>,
  5608. provides facilities for low-level programming including operations
  5609. that violate the type system. A package using <code>unsafe</code>
  5610. must be vetted manually for type safety and may not be portable.
  5611. The package provides the following interface:
  5612. </p>
  5613. <pre class="grammar">
  5614. package unsafe
  5615. type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type
  5616. type Pointer *ArbitraryType
  5617. func Alignof(variable ArbitraryType) uintptr
  5618. func Offsetof(selector ArbitraryType) uintptr
  5619. func Sizeof(variable ArbitraryType) uintptr
  5620. type IntegerType int // shorthand for an integer type; it is not a real type
  5621. func Add(ptr Pointer, len IntegerType) Pointer
  5622. func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
  5623. </pre>
  5624. <p>
  5625. A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
  5626. value may not be <a href="#Address_operators">dereferenced</a>.
  5627. Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
  5628. a type of underlying type <code>Pointer</code> and vice versa.
  5629. The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
  5630. </p>
  5631. <pre>
  5632. var f float64
  5633. bits = *(*uint64)(unsafe.Pointer(&amp;f))
  5634. type ptr unsafe.Pointer
  5635. bits = *(*uint64)(ptr(&amp;f))
  5636. var p ptr = nil
  5637. </pre>
  5638. <p>
  5639. The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
  5640. of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
  5641. as if <code>v</code> was declared via <code>var v = x</code>.
  5642. </p>
  5643. <p>
  5644. The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
  5645. <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
  5646. or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
  5647. If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
  5648. without pointer indirections through fields of the struct.
  5649. For a struct <code>s</code> with field <code>f</code>:
  5650. </p>
  5651. <pre>
  5652. uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&amp;s.f))
  5653. </pre>
  5654. <p>
  5655. Computer architectures may require memory addresses to be <i>aligned</i>;
  5656. that is, for addresses of a variable to be a multiple of a factor,
  5657. the variable's type's <i>alignment</i>. The function <code>Alignof</code>
  5658. takes an expression denoting a variable of any type and returns the
  5659. alignment of the (type of the) variable in bytes. For a variable
  5660. <code>x</code>:
  5661. </p>
  5662. <pre>
  5663. uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
  5664. </pre>
  5665. <p>
  5666. Calls to <code>Alignof</code>, <code>Offsetof</code>, and
  5667. <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
  5668. </p>
  5669. <p>
  5670. The function <code>Add</code> adds <code>len</code> to <code>ptr</code>
  5671. and returns the updated pointer <code>unsafe.Pointer(uintptr(ptr) + uintptr(len))</code>.
  5672. The <code>len</code> argument must be of integer type or an untyped <a href="#Constants">constant</a>.
  5673. A constant <code>len</code> argument must be <a href="#Representability">representable</a> by a value of type <code>int</code>;
  5674. if it is an untyped constant it is given type <code>int</code>.
  5675. The rules for <a href="/pkg/unsafe#Pointer">valid uses</a> of <code>Pointer</code> still apply.
  5676. </p>
  5677. <p>
  5678. The function <code>Slice</code> returns a slice whose underlying array starts at <code>ptr</code>
  5679. and whose length and capacity are <code>len</code>.
  5680. <code>Slice(ptr, len)</code> is equivalent to
  5681. </p>
  5682. <pre>
  5683. (*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
  5684. </pre>
  5685. <p>
  5686. except that, as a special case, if <code>ptr</code>
  5687. is <code>nil</code> and <code>len</code> is zero,
  5688. <code>Slice</code> returns <code>nil</code>.
  5689. </p>
  5690. <p>
  5691. The <code>len</code> argument must be of integer type or an untyped <a href="#Constants">constant</a>.
  5692. A constant <code>len</code> argument must be non-negative and <a href="#Representability">representable</a> by a value of type <code>int</code>;
  5693. if it is an untyped constant it is given type <code>int</code>.
  5694. At run time, if <code>len</code> is negative,
  5695. or if <code>ptr</code> is <code>nil</code> and <code>len</code> is not zero,
  5696. a <a href="#Run_time_panics">run-time panic</a> occurs.
  5697. </p>
  5698. <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
  5699. <p>
  5700. For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
  5701. </p>
  5702. <pre class="grammar">
  5703. type size in bytes
  5704. byte, uint8, int8 1
  5705. uint16, int16 2
  5706. uint32, int32, float32 4
  5707. uint64, int64, float64, complex64 8
  5708. complex128 16
  5709. </pre>
  5710. <p>
  5711. The following minimal alignment properties are guaranteed:
  5712. </p>
  5713. <ol>
  5714. <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
  5715. </li>
  5716. <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
  5717. all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
  5718. </li>
  5719. <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
  5720. the alignment of a variable of the array's element type.
  5721. </li>
  5722. </ol>
  5723. <p>
  5724. A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.
  5725. </p>