go_spec.html 201 KB

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