Learning Go: An Idiomatic Approach to Real-World Go Programming

Оглавление⌄
PrefaceWho Should Read This BookConventions Used in This BookUsing Code ExamplesO’Reilly Online LearningHow to Contact UsAcknowledgments1. Setting Up Your Go EnvironmentInstalling the Go ToolsThe Go WorkspaceThe go Commandgo run and go buildGetting Third-Party Go ToolsFormatting Your CodeLinting and VettingChoose Your ToolsVisual Studio CodeGoLandThe Go PlaygroundMakefilesStaying Up to DateWrapping Up2. Primitive Types and DeclarationsBuilt-in TypesThe Zero ValueLiteralsBooleansNumeric TypesA Taste of Strings and RunesExplicit Type Conversionvar Versus :=Using constTyped and Untyped ConstantsUnused VariablesNaming Variables and ConstantsWrapping Up3. Composite TypesArrays—Too Rigid to Use DirectlySliceslenappendCapacitymakeDeclaring Your SliceSlicing SlicesConverting Arrays to SlicescopyStrings and Runes and BytesMapsReading and Writing a MapThe comma ok IdiomDeleting from MapsUsing Maps as SetsStructsAnonymous StructsComparing and Converting StructsWrapping Up4. Blocks, Shadows, and Control StructuresBlocksShadowing VariablesDetecting Shadowed Variablesiffor, Four WaysThe Complete for StatementThe Condition-Only for StatementThe Infinite for Statementbreak and continueThe for-range StatementLabeling Your for StatementsChoosing the Right for StatementswitchBlank SwitchesChoosing Between if and switchgoto—Yes, gotoWrapping Up5. FunctionsDeclaring and Calling FunctionsSimulating Named and Optional ParametersVariadic Input Parameters and SlicesMultiple Return ValuesMultiple Return Values Are Multiple ValuesIgnoring Returned ValuesNamed Return ValuesBlank Returns—Never Use These!Functions Are ValuesFunction Type DeclarationsAnonymous FunctionsClosuresPassing Functions as ParametersReturning Functions from FunctionsdeferGo Is Call By ValueWrapping Up6. PointersA Quick Pointer PrimerDon’t Fear the PointersPointers Indicate Mutable ParametersPointers Are a Last ResortPointer Passing PerformanceThe Zero Value Versus No ValueThe Difference Between Maps and SlicesSlices as BuffersReducing the Garbage Collector’s WorkloadWrapping Up7. Types, Methods, and InterfacesTypes in GoMethodsPointer Receivers and Value ReceiversCode Your Methods for nil InstancesMethods Are Functions TooFunctions Versus MethodsType Declarations Aren’t InheritanceTypes Are Executable Documentationiota Is for Enumerations—SometimesUse Embedding for CompositionEmbedding Is Not InheritanceA Quick Lesson on InterfacesInterfaces Are Type-Safe Duck TypingEmbedding and InterfacesAccept Interfaces, Return StructsInterfaces and nilThe Empty Interface Says NothingType Assertions and Type SwitchesUse Type Assertions and Type Switches SparinglyFunction Types Are a Bridge to InterfacesImplicit Interfaces Make Dependency Injection EasierWireGo Isn’t Particularly Object-Oriented (and That’s Great)Wrapping Up8. ErrorsHow to Handle Errors: The BasicsUse Strings for Simple ErrorsSentinel ErrorsErrors Are ValuesWrapping ErrorsIs and AsWrapping Errors with deferpanic and recoverGetting a Stack Trace from an ErrorWrapping Up9. Modules, Packages, and ImportsRepositories, Modules, and Packagesgo.modBuilding PackagesImports and ExportsCreating and Accessing a PackageNaming PackagesHow to Organize Your ModuleOverriding a Package’s NamePackage Comments and godocThe internal PackageThe init Function: Avoid if PossibleCircular DependenciesGracefully Renaming and Reorganizing Your APIWorking with ModulesImporting Third-Party CodeWorking with VersionsMinimum Version SelectionUpdating to Compatible VersionsUpdating to Incompatible VersionsVendoringpkg.go.devAdditional InformationPublishing Your ModuleVersioning Your ModuleModule Proxy ServersSpecifying a Proxy ServerPrivate RepositoriesWrapping Up10. Concurrency in GoWhen to Use ConcurrencyGoroutinesChannelsReading, Writing, and Bufferingfor-range and ChannelsClosing a ChannelHow Channels BehaveselectConcurrency Practices and PatternsKeep Your APIs Concurrency-FreeGoroutines, for Loops, and Varying VariablesAlways Clean Up Your GoroutinesThe Done Channel PatternUsing a Cancel Function to Terminate a GoroutineWhen to Use Buffered and Unbuffered ChannelsBackpressureTurning Off a case in a selectHow to Time Out CodeUsing WaitGroupsRunning Code Exactly OncePutting Our Concurrent Tools TogetherWhen to Use Mutexes Instead of ChannelsAtomics—You Probably Don’t Need TheseWhere to Learn More About ConcurrencyWrapping Up11. The Standard Libraryio and FriendstimeMonotonic TimeTimers and Timeoutsencoding/jsonUse Struct Tags to Add MetadataUnmarshaling and MarshalingJSON, Readers, and WritersEncoding and Decoding JSON StreamsCustom JSON Parsingnet/httpThe ClientThe ServerWrapping Up12. The ContextWhat Is the Context?CancellationTimersHandling Context Cancellation in Your Own CodeValuesWrapping Up13. Writing TestsThe Basics of TestingReporting Test FailuresSetting Up and Tearing DownStoring Sample Test DataCaching Test ResultsTesting Your Public APIUse go-cmp to Compare Test ResultsTable TestsChecking Your Code CoverageBenchmarksStubs in GohttptestIntegration Tests and Build TagsFinding Concurrency Problems with the Race CheckerWrapping Up14. Here There Be Dragons: Reflect, Unsafe, and CgoReflection Lets Us Work with Types at RuntimeTypes, Kinds, and ValuesMaking New ValuesUse Reflection to Check If an Interface’s Value Is nilUse Reflection to Write a Data MarshalerBuild Functions with Reflection to Automate Repetitive TasksYou Can Build Structs with Reflection, but Don’tReflection Can’t Make MethodsOnly Use Reflection If It’s Worthwhileunsafe Is UnsafeUse unsafe to Convert External Binary Dataunsafe Strings and Slicesunsafe ToolsCgo Is for Integration, Not PerformanceWrapping Up15. A Look at the Future: Generics in GoGenerics Reduce Repetitive Code and Increase Type SafetyIntroducing Generics in GoUse Type Lists to Specify OperatorsGeneric Functions Abstract AlgorithmsType Lists Limit Constants and ImplementationsThings That Are Left OutIdiomatic Go and GenericsFurther Futures UnlockedWrapping UpIndex
Описание
Коротко и по делу о том, что важно знать про language.
While there are plenty of tutorials available that teach Go's syntax to developers with experience in other programming languages, tutorials aren't enough. Go is rapidly becoming the preferred language for building web services. They don't teach Go's idioms, so developers end up recreating patterns that don't make sense in a Go context. This practical guide provides the essential background you need to write clear and idiomatic Go.
Author Jon Bodner introduces the design patterns experienced Go developers have adopted and explores the rationale for using them. No matter your level of experience, you'll learn how to think like a Go developer. You'll also get a preview of Go's upcoming generics support and how it fits into the language.
Learn how to write idiomatic code in Go and design a Go projectUnderstand the reasons for the design decisions in GoSet up a Go development environment for a solo developer or teamLearn how and when to use reflection, unsafe, and cgoDiscover how Go's features allow the language to run efficientlyKnow which Go features you should use sparingly or not at all
Если материал оказался полезен — сохраните страницу.
Поделиться
Частые вопросы
Можно ли скачать «Learning Go: An Idiomatic Approach to Real-World Go Programming» бесплатно?
Да, «Learning Go: An Idiomatic Approach to Real-World Go Programming» доступна для бесплатного скачивания на нашем сайте в формате PDF. Ссылка на файл находится на этой странице.
В каком формате и какого размера файл?
Книга предоставляется в формате PDF, размер файла 2,3 МБ.
Кто автор и когда вышла книга?
автор — Bodner Jon, издательство O’Reilly Media, Inc., год выпуска 2021, 526 страниц.
О чём книга «Learning Go: An Idiomatic Approach to Real-World Go Programming»?
Go is rapidly becoming the preferred language for building web services.