O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Learning Go Programming

Book Description

An insightful guide to learning the Go programming language

About This Book

  • Insightful coverage of Go programming syntax, constructs, and idioms to help you understand Go code effectively
  • Push your Go skills, with topics such as, data types, channels, concurrency, object-oriented Go, testing, and network programming
  • Each chapter provides working code samples that are designed to help reader quickly understand respective topic

Who This Book Is For

If you have prior exposure to programming and are interested in learning the Go programming language, this book is designed for you. It will quickly run you through the basics of programming to let you exploit a number of features offered by Go programming language.

What You Will Learn

  • Install and configure the Go development environment to quickly get started with your first program.
  • Use the basic elements of the language including source code structure, variables, constants, and control flow primitives to quickly get started with Go
  • Gain practical insight into the use of Go's type system including basic and composite types such as maps, slices, and structs.
  • Use interface types and techniques such as embedding to create idiomatic object-oriented programs in Go.
  • Develop effective functions that are encapsulated in well-organized package structures with support for error handling and panic recovery.
  • Implement goroutine, channels, and other concurrency primitives to write highly-concurrent and safe Go code
  • Write tested and benchmarked code using Go’s built test tools
  • Access OS resources by calling C libraries and interact with program environment at runtime

In Detail

The Go programming language has firmly established itself as a favorite for building complex and scalable system applications. Go offers a direct and practical approach to programming that let programmers write correct and predictable code using concurrency idioms and a full-featured standard library.

This is a step-by-step, practical guide full of real world examples to help you get started with Go in no time at all. We start off by understanding the fundamentals of Go, followed by a detailed description of the Go data types, program structures and Maps. After this, you learn how to use Go concurrency idioms to avoid pitfalls and create programs that are exact in expected behavior. Next, you will be familiarized with the tools and libraries that are available in Go for writing and exercising tests, benchmarking, and code coverage.

Finally, you will be able to utilize some of the most important features of GO such as, Network Programming and OS integration to build efficient applications. All the concepts are explained in a crisp and concise manner and by the end of this book; you would be able to create highly efficient programs that you can deploy over cloud.

Style and approach

The book is written to serve as a reader-friendly step-by-step guide to learning the Go programming language. Each topic is sequentially introduced to build on previous materials covered. Every concept is introduced with easy-to-follow code examples that focus on maximizing the understanding of the topic at hand.

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

Table of Contents

  1. Learning Go Programming
    1. Learning Go Programming
    2. Credits
    3. About the Author
    4. About the Reviewers
    5. www.PacktPub.com
      1. Why subscribe?
    6. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Downloading the color images of this book
        3. Errata
        4. Piracy
        5. Questions
    7. 1. A First Step in Go
      1. The Go programming language
      2. Playing with Go
        1. No IDE required
        2. Installing Go
        3. Source code examples
      3. Your first Go program
      4. Go in a nutshell
        1. Functions
        2. Packages
        3. The workspace
        4. Strongly typed
        5. Composite types
        6. The named type
        7. Methods and objects
        8. Interfaces
        9. Concurrency and channels
        10. Memory management and safety
        11. Fast compilation
        12. Testing and code coverage
        13. Documentation
        14. An extensive library
        15. The Go Toolchain
      5. Summary
    8. 2. Go Language Essentials
      1. The Go source file
        1. Optional semicolon
        2. Multiple lines
      2. Go identifiers
        1. The blank identifier
        2. Muting package imports
        3. Muting unwanted function results
        4. Built-in identifiers
          1. Types
          2. Values
          3. Functions
      3. Go variables
        1. Variable declaration
        2. The zero-value
        3. Initialized declaration
        4. Omitting variable types
        5. Short variable declaration
        6. Restrictions for short variable declaration
        7. Variable scope and visibility
        8. Variable declaration block
      4. Go constants
        1. Constant literals
        2. Typed constants
        3. Untyped constants
        4. Assigning untyped constants
        5. Constant declaration block
        6. Constant enumeration
        7. Overriding the default enumeration type
        8. Using iota in expressions
        9. Skipping enumerated values
      5. Go operators
        1. Arithmetic operators
        2. The increment and decrement operators
        3. Go assignment operators
        4. Bitwise operators
        5. Logical Operators
        6. Comparison operators
        7. Operator precedence
      6. Summary
    9. 3. Go Control Flow
      1. The if statement
        1. The if statement initialization
      2. Switch statements
        1. Using expression switches
        2. The fallthrough cases
        3. Expressionless switches
        4. Switch initializer
        5. Type switches
      3. The for statements
        1. For condition
        2. Infinite loop
        3. The traditional for statement
        4. The for range
      4. The break, continue, and goto statements
        1. The label identifier
        2. The break statement
        3. The continue statement
        4. The goto statement
      5. Summary
    10. 4. Data Types
      1. Go types
      2. Numeric types
        1. Unsigned integer types
        2. Signed integer types
        3. Floating point types
        4. Complex number types
        5. Numeric literals
      3. Boolean type
      4. Rune and string types
        1. The rune
        2. The string
        3. Interpreted and raw string literals
      5. Pointers
        1. The pointer type
        2. The address operator
        3. The new() function
        4. Pointer indirection - accessing referenced values
      6. Type declaration
      7. Type conversion
      8. Summary
    11. 5. Functions in Go
      1. Go functions
        1. Function declaration
        2. The function type
        3. Variadic parameters
        4. Function result parameters
          1. Named result parameters
      2. Passing parameter values
        1. Achieving pass-by-reference
        2. Anonymous Functions and Closures
        3. Invoking anonymous function literals
        4. Closures
      3. Higher-order functions
      4. Error signaling and handling
        1. Signaling errors
        2. Error handling
        3. The error type
      5. Deferring function calls
        1. Using defer
      6. Function panic and recovery
        1. Function panic
        2. Function panic recovery
      7. Summary
    12. 6. Go Packages and Programs
      1. The Go package
        1. Understanding the Go package
        2. The workspace
        3. Creating a workspace
        4. The import path
      2. Creating packages
        1. Declaring the package
        2. Multi-File packages
        3. Naming packages
          1. Use globally unique namespaces
          2. Add context to path
          3. Use short names
      3. Building packages
        1. Installing a package
      4. Package visibility
        1. Package member visibility
      5. Importing package
        1. Specifying package identifiers
        2. The dot identifier
        3. The blank identifier
      6. Package initialization
      7. Creating programs
        1. Accessing program arguments
        2. Building and installing programs
      8. Remote packages
      9. Summary
    13. 7. Composite Types
      1. The array type
        1. Array initialization
        2. Declaring named array types
        3. Using arrays
        4. Array length and capacity
        5. Array traversal
        6. Array as parameters
      2. The slice type
        1. Slice initialization
        2. Slice representation
        3. Slicing
        4. Slicing a slice
        5. Slicing an array
        6. Slice expressions with capacity
        7. Making a slice
        8. Using slices
        9. Slices as parameters
        10. Length and capacity
        11. Appending to slices
        12. Copying slices
        13. Strings as slices
      3. The map type
        1. Map initialization
        2. Making Maps
        3. Using maps
        4. Map traversal
        5. Map functions
          1. Maps as parameters
      4. The struct type
        1. Accessing struct fields
        2. Struct initialization
        3. Declaring named struct types
        4. The anonymous field
          1. Promoted fields
        5. Structs as parameters
        6. Field tags
      5. Summary
    14. 8. Methods, Interfaces, and Objects
      1. Go methods
        1. Value and pointer receivers
      2. Objects in Go
        1. The struct as object
        2. Object composition
        3. Field and method promotion
        4. The constructor function
      3. The interface type
        1. Implementing an interface
        2. Subtyping with Go interfaces
        3. Implementing multiple interfaces
        4. Interface embedding
        5. The empty interface type
      4. Type assertion
      5. Summary
    15. 9. Concurrency
      1. Goroutines
        1. The go statement
        2. Goroutine scheduling
      2. Channels
        1. The Channel type
          1. The send and receive operations
        2. Unbuffered channel
        3. Buffered channel
        4. Unidirectional channels
        5. Channel length and capacity
        6. Closing a channel
      3. Writing concurrent programs
        1. Synchronization
        2. Streaming data
        3. Using for…range to receive data
        4. Generator functions
        5. Selecting from multiple channels
        6. Channel timeout
      4. The sync package
        1. Synchronizing with mutex locks
        2. Synchronizing access to composite values
        3. Concurrency barriers with sync.WaitGroup
      5. Detecting race conditions
      6. Parallelism in Go
      7. Summary
    16. 10. Data IO in Go
      1. IO with readers and writers
      2. The io.Reader interface
        1. Chaining readers
      3. The io.Writer interface
      4. Working with the io package
      5. Working with files
        1. Creating and opening files
        2. Function os.OpenFile
        3. Files writing and reading
        4. Standard input, output, and error
      6. Formatted IO with fmt
        1. Printing to io.Writer interfaces
        2. Printing to standard output
        3. Reading from io.Reader
        4. Reading from standard input
      7. Buffered IO
        1. Buffered writers and readers
        2. Scanning the buffer
      8. In-memory IO
      9. Encoding and decoding data
        1. Binary encoding with gob
        2. Encoding data as JSON
        3. Controlling JSON mapping with struct tags
        4. Custom encoding and decoding
      10. Summary
    17. 11. Writing Networked Services
      1. The net package
        1. Addressing
        2. The net.Conn Type
        3. Dialing a connection
        4. Listening for incoming connections
        5. Accepting client connections
      2. A TCP API server
        1. Connecting to the TCP server with telnet
        2. Connecting to the TCP server with Go
      3. The HTTP package
        1. The http.Client type
        2. Configuring the client
        3. Handling client requests and responses
        4. A simple HTTP server
          1. The default server
        5. Routing requests with http.ServeMux
          1. The default ServeMux
      4. A JSON API server
        1. Testing the API server with cURL
        2. An API server client in Go
        3. A JavaScript API server client
      5. Summary
    18. 12. Code Testing
      1. The Go test tool
        1. Test file names
        2. Test organization
      2. Writing Go tests
        1. The test functions
        2. Running the tests
          1. Filtering executed tests
        3. Test logging
        4. Reporting failure
        5. Skipping tests
        6. Table-driven tests
      3. HTTP testing
        1. Testing HTTP server code
        2. Testing HTTP client code
      4. Test coverage
        1. The cover tool
      5. Code benchmark
        1. Running the benchmark
        2. Skipping test functions
        3. The benchmark report
        4. Adjusting N
        5. Comparative benchmarks
      6. Summary