go_spec.html 282 KB

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