Example: bankruptcy

The Go Programming Language Phrasebook

David ChisnallThe Go ProgrammingLanguagePHRASEBOOKU pper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCape Town Sydney Tokyo Singapore Mexico CityDEVELOPER SLIBRARYMany of the designations used by manufacturers and sellers to distinguish theirproducts are claimed as trademarks. Where those designations appear in this book,and the publisher was aware of a trademark claim, the designations have been print-ed with initial capital letters or in all author and publisher have taken care in the preparation of this book, but makeno expressed or implied warranty of any kind and assume no responsibility for errorsor omissions. No liability is assumed for incidental or consequential damages in con-nection with or arising out of the use of the information or programs contained publisher offers excellent discounts on this book when ordered in quantity forbulk purchases or special sales, which may include electronic versions and/or cus-tom covers and content particular to your business, training goals, marketing focus,and branding interests.

Table of Contents 1 Introducing Go 1 Go and C 1 Why Go? 4 Goroutines and Channels 7 Selecting a Compiler 10 Creating a Simple Go Program 13 The Go Type System 14

Tags:

  Programming, Language, Phrasebook, The go programming language phrasebook, The go

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of The Go Programming Language Phrasebook

1 David ChisnallThe Go ProgrammingLanguagePHRASEBOOKU pper Saddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCape Town Sydney Tokyo Singapore Mexico CityDEVELOPER SLIBRARYMany of the designations used by manufacturers and sellers to distinguish theirproducts are claimed as trademarks. Where those designations appear in this book,and the publisher was aware of a trademark claim, the designations have been print-ed with initial capital letters or in all author and publisher have taken care in the preparation of this book, but makeno expressed or implied warranty of any kind and assume no responsibility for errorsor omissions. No liability is assumed for incidental or consequential damages in con-nection with or arising out of the use of the information or programs contained publisher offers excellent discounts on this book when ordered in quantity forbulk purchases or special sales, which may include electronic versions and/or cus-tom covers and content particular to your business, training goals, marketing focus,and branding interests.

2 For more information, please Corporate and Government Sales(800) sales outside the United States, please contact:International us on the Web: of Congress Cataloging-in-Publication Data:Chisnall, Go Programming Language Phrasebook / David 978-0-321-81714-3 (pbk. : alk. paper) ISBN 0-321-81714-1 (pbk. : )1. Go (Computer program Language ) 2. Computer Programming . 3. Open sourcesoftware. I. Title. dc232012000478 Copyright 2012 Pearson Education, rights reserved. Printed in the United States of America. This publication is pro-tected by copyright, and permission must be obtained from the publisher prior to anyprohibited reproduction, storage in a retrieval system, or transmission in any form orby any means, electronic, mechanical, photocopying, recording, or likewise.

3 To obtainpermission to use material from this work, please submit a written request toPearson Education, Inc., Permissions Department, One Lake Street, Upper SaddleRiver, New Jersey 07458, or you may fax your request to (201) : 978- 0-321-81714-3 ISBN-10: 0-321-81714-1 Text printed in the United States on recycled paper at Edwards Brothers Malloy inAnn Arbor, printing: March 2012 Editor-in-ChiefMark TaubAcquisitions EditorDebra WilliamsCauleyMarketingManagerStephane NakibManaging EditorKristy HartProject EditorAnne GoebelCopy EditorGayle JohnsonPublishingCoordinatorAndrea BledsoeCover DesignerGary AdairSenior CompositorGloria SchurickTable of Contents1 Introducing Go1Go and C1 Why Go?4 Goroutines and Channels7 Selecting a Compiler10 Creating a Simple Go Program13 the go Type System14 Understanding the Memory Model162 A Go Primer21 The Structure of a Go Source File23 Declaring Variables26 Declaring Functions29 Looping in Go32 Creating Enumerations35 Declaring Structures37 Defining Methods39 Implementing Interfaces42 Casting Types473 Numbers51 Converting Between Strings and Numbers52 Using Large Integers54 Converting Between Numbers and Pointers564 Common Go Patterns61ivContentsZero Initialization62 Generic Data Structures67 Specialized Generic Data Structures69 Implementation Hiding72 Type Embedding755 Arrays and Slices79 Creating Arrays81 Slicing Arrays83 Resizing Slices85 Truncating Slices87 Iterating Over Arrays886 Manipulating Strings91 Comparing Strings92

4 Processing a String One Character at aTime94 Processing a Partial String96 Splitting and Trimming Strings98 Copying Strings102 Creating Strings from Patterns102 Matching Patterns in Strings1047 Working with Collections107 Creating a Map108 Storing Unordered Groups of Objects111 Using Lists112 Defining New Collections114 Contentsv8 Handling Errors117 Deferring Cleanup118 Panicking and Recovering121 Returning Error Values125 Error Delegates1279 Goroutines131 Creating Goroutines131 Synchronizing Goroutines134 Waiting for a Condition137 Performing Thread-Safe Initialization140 Performing Actions in the Background142 Communicating Via Channels144 Using Multiple Channels14810 Concurrency Design Patterns151 Timing Out Connections152 Aliased xor Mutable154 Share Memory by Communicating156 Transactions by Sharing Channels159 Concurrent Objects162 Implementing Futures in Go164 Coalescing Events166 Map Reduce.

5 Go Style16811 Dates and Times175 Finding the Current Date176 Converting Dates for Display177viContentsParsing Dates from Strings179 Calculating Elapsed Time180 Receiving Timer Events18112 Accessing Files and the Environment 183 Manipulating Paths184 Reading a File186 Reading One Line at a Time188 Determining if a File or Directory Exists190 Checking Environment Variables19213 Network Access195 Connecting to Servers196 Distributing Go199 Serving Objects204 Calling Remote Procedures20614 Web Applications207 Integrating with a Web Server208 Connecting to Web Servers211 Parsing HTML213 Generating HTML21615 Interacting with the go Runtime219 Finding the Type of a Variable220 Finalizing Structures223 Copying Arbitrary Types226 Constructing Function Calls228 Calling C Functions230 Contentsvii16 Distributing Go Code233 Installing Third-Party Packages234 Creating Packages236 Documenting Your Code240 Staying Up to Date24117 Debugging Go243 Using a Debugger243 Misunderstanding Memory Ordering247 Spotting Concurrency Bugs249 Restricting Behavior252 Building Unit Tests257 Index259 This page intentionally left blank About the AuthorDavid Chisnall is a freelance writer and studying for his PhD, he cofounded the toil project, which aims to produce an open-source desktop environment on top of GNUstep,an open-source implementation of the OpenStepand Cocoa APIs.

6 He is an active contributorto GNUstep and is the original author andmaintainer of the GNUstep Objective-C 2runtime library and the associated compilersupport in the Clang compiler. He is also aFreeBSD committer working various aspects ofthe toolchain, including being responsible for thenew C++ completing his PhD, David hid in academiafor a while, studying the history of programminglanguages. He finally escaped when he realizedthat there were places off campus with anequally good view of the sea and withoutthe requirement to complete quite so muchpaperwork. He occasionally returns to collaborateon projects involving modeling the semantics ofdynamic not writing or Programming , David enjoysdancing Argentine tango and Cuban salsa,playing badminton and ultimate frisbee, first person I d like to thank is MarkSummerfield, author ofProgramming in Go:Creating Applications for the 21st finish this book and want to learn more, I drecommend you pick up a copy.

7 Mark was theperson responsible for making me look at Go inthe first next person I need to thank is YoshikiShibata. Yoshiki has been working on theJapanese translation of this book and, in doingso, has sent me countless emails highlightingareas that could be improved. If you enjoyreading this book then Yoshiki deserves a lot ofthe , I need to thank everyone else who wasinvolved in bringing this book from my texteditor to your hands. A lot of people haveearned some credit along the way. In particular,Debra Williams-Cauley, who masterminded theproject, and Anne Goebel, who shepherded thebook from a draft manuscript to the version younow Go PrimerOne of the goals of Go was a consistent andunambiguous syntax. This makes it easy fortools to examine Go programs, and also makesit easy to learn.

8 Unhelpful compiler errors makeit difficult to learn a Language , as anyone whohas made a typo in C++ code using templateswill C, for example, function and global variabledeclarations have almost the same syntax. Thismeans that the compiler can t easily tell whichone you meant if you make an error. It gives youhelpful error messages like expected ; on a linewhere you don t think a semicolon is expected Go grammar was designed to make itpossible for the compiler to tell you moreaccurately what you did wrong. It was alsodesigned to avoid the need to state somethingthat can be easily inferred. For example, if youcreate a variable and set its value to 42, the22 CHAPTER 2:A Go Primercompiler could probably guess that this variableshould be an integer, without it being explicitlystated.

9 If you initialize it with a function call,then the compiler can definitely tell that thetype should be whatever the function was the same problem that C++ 2011solves with adopts JavaScript s idea ofsemicoloninsertion, and takes it a step further. Any linethat can be interpreted as a complete statementhas a semicolon implicitly inserted at the end bythe means that Go programs canfreely omit semicolons as statement adds some constraints, for exampleenforcing a brace style where open braces are atthe end of the line at the start of flow-controlstatements, rather than on their own. If youhappen to be a human, this is unfortunate,because it means that you can t use the highlyoptimized symmetry recognition paths, whichevolution has spent the last million or so yearsoptimizing in your visual cortex, for recognizingcode chapter contains an overview of Go is not a complete reference.

10 Some aspectsare covered in later chapters. In particular, allof the concurrency-related aspects of Go arecovered in Chapter 9, is an oversimplification. The exact rules forsemicolon insertion are more complicated, but this rule ofthumb works in most Structure of a Go Source File23 The Structure of a Go SourceFile1packagemain2import"fmt"34func main() { ("Hello World!\n")6}From: Go source file consists of three parts. The firstis apackagestatement. Go code is arranged inpackages, which fill the r les of both librariesand header files in C. The package in thisexample is calledmain, which is special. Everyprogram must contain amainpackage, whichcontains amain()function, which is the programentry next section specifies the packages that thisfile uses and how they should be imported.


Related search queries