go_spec.html 253 KB

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