100% found this document useful (3 votes)
16 views

Go for Java Programmers: Learn the Google Go Programming Language 1st Edition Barry Feigenbaum pdf download

The document provides information about the book 'Go for Java Programmers: Learn the Google Go Programming Language' by Barry Feigenbaum, which is designed for Java programmers transitioning to Go. It includes details about the book's content, comparisons between Go and Java, and various programming concepts. Additionally, it offers links to other related programming books and resources available for download.

Uploaded by

myreskricksm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
16 views

Go for Java Programmers: Learn the Google Go Programming Language 1st Edition Barry Feigenbaum pdf download

The document provides information about the book 'Go for Java Programmers: Learn the Google Go Programming Language' by Barry Feigenbaum, which is designed for Java programmers transitioning to Go. It includes details about the book's content, comparisons between Go and Java, and various programming concepts. Additionally, it offers links to other related programming books and resources available for download.

Uploaded by

myreskricksm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Go for Java Programmers: Learn the Google Go

Programming Language 1st Edition Barry


Feigenbaum install download

https://ebookmeta.com/product/go-for-java-programmers-learn-the-
google-go-programming-language-1st-edition-barry-feigenbaum/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Network Programming with Go Language: Essential Skills


for Programming, Using and Securing Networks with Open
Source Google Golang 2nd Edition Jan Newmarch

https://ebookmeta.com/product/network-programming-with-go-
language-essential-skills-for-programming-using-and-securing-
networks-with-open-source-google-golang-2nd-edition-jan-
newmarch-2/

Network Programming with Go Language : Essential Skills


for Programming, Using and Securing Networks with Open
Source Google Golang 2nd Edition Jan Newmarch

https://ebookmeta.com/product/network-programming-with-go-
language-essential-skills-for-programming-using-and-securing-
networks-with-open-source-google-golang-2nd-edition-jan-newmarch/

Learn Concurrent Programming with Go (MEAP v02) James


Cutajar

https://ebookmeta.com/product/learn-concurrent-programming-with-
go-meap-v02-james-cutajar/

Testing for Language Teachers 3rd Edition Arthur Hughes

https://ebookmeta.com/product/testing-for-language-teachers-3rd-
edition-arthur-hughes-2/
The Religion of Ethnicity 1st Edition Gary A Kunkelman

https://ebookmeta.com/product/the-religion-of-ethnicity-1st-
edition-gary-a-kunkelman/

Wolf Inn Complete Series Box Set 1st Edition Layla


Silver

https://ebookmeta.com/product/wolf-inn-complete-series-box-
set-1st-edition-layla-silver/

Future Networks, Services and Management: Underlay and


Overlay, Edge, Applications, Slicing, Cloud, Space,
AI/ML, and Quantum Computing 1st Edition Mehmet Toy

https://ebookmeta.com/product/future-networks-services-and-
management-underlay-and-overlay-edge-applications-slicing-cloud-
space-ai-ml-and-quantum-computing-1st-edition-mehmet-toy/

Ultimate Harley Davidson New Edition Hugo Wilson

https://ebookmeta.com/product/ultimate-harley-davidson-new-
edition-hugo-wilson/

Tietz Fundamentals of Clinical Chemistry and Molecular


Diagnostics Nader Rifai

https://ebookmeta.com/product/tietz-fundamentals-of-clinical-
chemistry-and-molecular-diagnostics-nader-rifai/
Science, Public Health and Nation-Building in Soekarno-
Era Indonesia 1st Edition Vivek Neelakantan

https://ebookmeta.com/product/science-public-health-and-nation-
building-in-soekarno-era-indonesia-1st-edition-vivek-neelakantan/
Go for Java
Programmers
Learn the Google Go Programming
Language

Barry Feigenbaum, Ph.D.
Go for Java Programmers
Learn the Google
Go Programming Language

Barry Feigenbaum, Ph.D.


Go for Java Programmers: Learn the Google Go Programming Language

Barry Feigenbaum, Ph.D.


Austin, TX, USA

ISBN-13 (pbk): 978-1-4842-7198-8 ISBN-13 (electronic): 978-1-4842-7199-5 


https://doi.org/10.1007/978-1-4842-7199-5
Copyright © 2022 by Barry Feigenbaum
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image by Ricardo Gomez on Unsplash (www.unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.
springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science
+ Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484271988. For more
detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
To my wife Martha who sustains me.

Thank you for putting up with all the time


I spent working on this book.

This book was developed during the Covid-19 pandemic.


Many thanks and kudos to all the health-care workers that served so
many that became ill and to the essential workers that keep the country
going during this time of crisis. My heart goes out to the many who lost
friends and loved ones due to Covid-19. May time reduce your pain.
Personally, the stay-at-home nature of this crisis offered me the time
needed to author this book, so in some way is it a, hopefully, positive
by-product of the pandemic.
Table of Contents
About the Author��������������������������������������������������������������������������������������������������� xiii

About the Technical Reviewer���������������������������������������������������������������������������������xv


Acknowledgments�������������������������������������������������������������������������������������������������xvii

Introduction������������������������������������������������������������������������������������������������������������xix

Assessments�������������������������������������������������������������������������������������������������������xxxv

Part I: First Look at Go������������������������������������������������������������������������������������ 1


Chapter 1: A Brief Look at Go vs. Java��������������������������������������������������������������������� 5
Go Is a Compiled (vs. Interpreted, As Java Is) Language�������������������������������������������������������������� 6
Go and Java Share Similar Program Structure����������������������������������������������������������������������������� 7
Go and Java Have Some Code Style Differences That Influence How Code Is Structured������������ 7
Both Go and Java Are Procedural Languages������������������������������������������������������������������������������� 8
Java Is an Object-Oriented (OO) Language, While Go Is Not Fully OO������������������������������������������� 9
Java Is a Highly Functional Language, Go Is Less So������������������������������������������������������������������ 10
Java Is a Highly Declarative Language, Go Is Less So���������������������������������������������������������������� 10
Many Java Features Are Annotation Driven�������������������������������������������������������������������������������� 10
Go Does Not Support Exceptions������������������������������������������������������������������������������������������� 11
Both Java and Go Use Managed Memory (Garbage Collectors)�������������������������������������������������� 11
Go and Java Both Support Concurrency but in Different Ways��������������������������������������������������� 12
Go’s Runtime Is Simpler Than the JRE���������������������������������������������������������������������������������������� 12
The Go Program Build Process Is Different��������������������������������������������������������������������������������� 13
Go and Java Have Similar Release Cycles���������������������������������������������������������������������������������� 13

v
Table of Contents

Chapter 2: What Java Has That Go Does Not���������������������������������������������������������� 15


Multiple Assignments������������������������������������������������������������������������������������������������������������������ 15
Statements and Operators���������������������������������������������������������������������������������������������������������� 15
Assert Statement������������������������������������������������������������������������������������������������������������������������ 16
While and Do Statements������������������������������������������������������������������������������������������������������������ 16
Throw Statement/Throws Clause������������������������������������������������������������������������������������������������ 17
Strictfp, transient, volatile, synchronized, abstract, static���������������������������������������������������������� 17
Objects and Classes (OOP) and Inner Classes, Lambdas, this, super, Explicit Constructors������� 17
Generic Types and Methods�������������������������������������������������������������������������������������������������������� 20
Extensive Functional Programming Capabilities������������������������������������������������������������������������� 20
Boxing of Primitive Values���������������������������������������������������������������������������������������������������������� 21
Source Annotations��������������������������������������������������������������������������������������������������������������������� 21
Multiple Visibilities���������������������������������������������������������������������������������������������������������������������� 22
Overloaded/Overridden Functions����������������������������������������������������������������������������������������������� 22
Formal Enums����������������������������������������������������������������������������������������������������������������������������� 22
Built-in Binary Data Self-Serialization���������������������������������������������������������������������������������������� 23
Concurrent Collections���������������������������������������������������������������������������������������������������������������� 23

Chapter 3: A Deeper Comparison of Go and Java��������������������������������������������������� 25

Part II: The Go Language������������������������������������������������������������������������������� 31


Chapter 4: Key Go Aspects������������������������������������������������������������������������������������� 33
Simple Go Program Example������������������������������������������������������������������������������������������������������ 35
Go Packages������������������������������������������������������������������������������������������������������������������������������� 41
Go Comments������������������������������������������������������������������������������������������������������������������������������ 44
Go Build/Run Process������������������������������������������������������������������������������������������������������������������ 45
Go Playground����������������������������������������������������������������������������������������������������������������������� 46
Go Integrated Development Environments���������������������������������������������������������������������������� 50
Running Go Programs������������������������������������������������������������������������������������������������������������ 55
Building Go Programs������������������������������������������������������������������������������������������������������������ 56
Bytecode vs. Real Code��������������������������������������������������������������������������������������������������������� 59

vi
Table of Contents

Go Command-Line Tools������������������������������������������������������������������������������������������������������������� 61
Tools Bundled in the Go Command���������������������������������������������������������������������������������������� 62
Other Tools����������������������������������������������������������������������������������������������������������������������������� 64
Go Runs Programs Instead of Classes���������������������������������������������������������������������������������������� 64
Go Memory Management������������������������������������������������������������������������������������������������������������ 66
Go Identifiers������������������������������������������������������������������������������������������������������������������������������� 71
Go Scopes����������������������������������������������������������������������������������������������������������������������������������� 73
Go Scopes vs. Go Source Files���������������������������������������������������������������������������������������������� 76
Initializing Go Variables��������������������������������������������������������������������������������������������������������������� 78
Lifetimes of Go Identifiers����������������������������������������������������������������������������������������������������������� 80
Go Module Summary������������������������������������������������������������������������������������������������������������������� 81
Go Assignments and Expressions����������������������������������������������������������������������������������������������� 87
Text Formatting in Go������������������������������������������������������������������������������������������������������������������ 89
Goroutines����������������������������������������������������������������������������������������������������������������������������������� 94
Issues with Concurrency������������������������������������������������������������������������������������������������������� 94
Go Concurrency��������������������������������������������������������������������������������������������������������������������� 97
Goroutines by Example�������������������������������������������������������������������������������������������������������� 100

Chapter 5: Go Basic Features������������������������������������������������������������������������������� 111


Language Keywords������������������������������������������������������������������������������������������������������������������ 111
Operators and Punctuation������������������������������������������������������������������������������������������������������� 114
Go Operator Precedence����������������������������������������������������������������������������������������������������������� 119
Go Built-in Functions����������������������������������������������������������������������������������������������������������������� 120

Chapter 6: Go Types���������������������������������������������������������������������������������������������� 123


Primitive/Built-in Types������������������������������������������������������������������������������������������������������������� 123
Numbers������������������������������������������������������������������������������������������������������������������������������ 123
Characters and Strings�������������������������������������������������������������������������������������������������������� 125
Reference vs. Pointer Types������������������������������������������������������������������������������������������������ 126
Drill Down on Basic Data Types������������������������������������������������������������������������������������������� 129
Methods As Functions��������������������������������������������������������������������������������������������������������� 152
Any Declared Type Can Have Custom Functions����������������������������������������������������������������� 153

vii
Table of Contents

Functions As Values������������������������������������������������������������������������������������������������������������� 155


Structure Fields������������������������������������������������������������������������������������������������������������������� 162
Structure Literals����������������������������������������������������������������������������������������������������������������� 164
Nested Structures���������������������������������������������������������������������������������������������������������������� 165
Structure Field Alignment���������������������������������������������������������������������������������������������������� 167
Application of Interfaces������������������������������������������������������������������������������������������������������ 171
Composite Interfaces����������������������������������������������������������������������������������������������������������� 174
Variable Declarations���������������������������������������������������������������������������������������������������������������� 179
Constant Declarations��������������������������������������������������������������������������������������������������������������� 182
Type Casting������������������������������������������������������������������������������������������������������������������������������ 184
Type Testing������������������������������������������������������������������������������������������������������������������������������ 185
Derived Type Declarations��������������������������������������������������������������������������������������������������������� 188

Chapter 7: Errors and Panics�������������������������������������������������������������������������������� 193


Go Errors����������������������������������������������������������������������������������������������������������������������������������� 193
Go Panics���������������������������������������������������������������������������������������������������������������������������������� 195
Errors and Panics Illustrated����������������������������������������������������������������������������������������������������� 199

Chapter 8: Go Statements������������������������������������������������������������������������������������� 207


Package and Import Statements����������������������������������������������������������������������������������������������� 208
Assignment Statements������������������������������������������������������������������������������������������������������������ 209
Declaring Variables������������������������������������������������������������������������������������������������������������������� 211
Declaring Named Constants����������������������������������������������������������������������������������������������������� 213
If/Else Statements��������������������������������������������������������������������������������������������������������������������� 214
Switch Statement��������������������������������������������������������������������������������������������������������������������� 217
While Statement������������������������������������������������������������������������������������������������������������������������ 220
Do-While Statement������������������������������������������������������������������������������������������������������������������ 221
For with Index Statement���������������������������������������������������������������������������������������������������������� 221
For over a Collection Statement������������������������������������������������������������������������������������������������ 222
Forever Statement�������������������������������������������������������������������������������������������������������������������� 224
Break and Continue Statements����������������������������������������������������������������������������������������������� 225
Goto Statement������������������������������������������������������������������������������������������������������������������������� 226

viii
Table of Contents

Return Statement���������������������������������������������������������������������������������������������������������������������� 227


Defer Statement������������������������������������������������������������������������������������������������������������������������ 228
Go Statement���������������������������������������������������������������������������������������������������������������������������� 229
Select Statement���������������������������������������������������������������������������������������������������������������������� 230

Chapter 9: Applications for Interfaces������������������������������������������������������������������ 233


An Interface Is the Key�������������������������������������������������������������������������������������������������������������� 233
On Dependency Injection���������������������������������������������������������������������������������������������������������� 236
On Aspect-Oriented Programming�������������������������������������������������������������������������������������������� 244

Chapter 10: Go Unit Tests and Benchmarks��������������������������������������������������������� 249


Test Cases and Benchmarks in Go�������������������������������������������������������������������������������������������� 250
Test Cases in Java��������������������������������������������������������������������������������������������������������������������� 262

Chapter 11: Going into the Future������������������������������������������������������������������������� 267


Improved Error Handling����������������������������������������������������������������������������������������������������������� 267
Go Generics������������������������������������������������������������������������������������������������������������������������������� 269
Capstone Game of Life Example����������������������������������������������������������������������������������������������� 275
Game of Life Go Source������������������������������������������������������������������������������������������������������������ 280
Capstone Project in Java����������������������������������������������������������������������������������������������������� 281
Capstone Project in Go�������������������������������������������������������������������������������������������������������� 326
API Outputs������������������������������������������������������������������������������������������������������������������������������� 355
Game Outputs��������������������������������������������������������������������������������������������������������������������������� 359

Part III: Go Library Survey�������������������������������������������������������������������������� 363


Chapter 12: Key Package Comparison������������������������������������������������������������������ 375
Java Lang Packages����������������������������������������������������������������������������������������������������������������� 375
Java IO Package������������������������������������������������������������������������������������������������������������������������ 380
Java Text Package��������������������������������������������������������������������������������������������������������������������� 383
Java Time Packages����������������������������������������������������������������������������������������������������������������� 385
Java Util Packages�������������������������������������������������������������������������������������������������������������������� 386

ix
Table of Contents

Chapter 13: Key Method/Function Comparison���������������������������������������������������� 393

Chapter 14: Go Package Survey��������������������������������������������������������������������������� 399


File Access with Go������������������������������������������������������������������������������������������������������������������� 399
Compression Services�������������������������������������������������������������������������������������������������������������� 402
Archive Packages���������������������������������������������������������������������������������������������������������������� 402
Compression Packages������������������������������������������������������������������������������������������������������� 405
Image���������������������������������������������������������������������������������������������������������������������������������������� 406
Input/Output (I/O)���������������������������������������������������������������������������������������������������������������������� 409
Bytes Package�������������������������������������������������������������������������������������������������������������������������� 415
Format Package������������������������������������������������������������������������������������������������������������������������ 419
Data Collections������������������������������������������������������������������������������������������������������������������������ 421
Sorting�������������������������������������������������������������������������������������������������������������������������������������� 424
Context Package����������������������������������������������������������������������������������������������������������������������� 426
Cryptography and Hashing and Data Encoding������������������������������������������������������������������������� 430
Encoding Packages������������������������������������������������������������������������������������������������������������������� 431
Unicode Encoding Packages����������������������������������������������������������������������������������������������� 433

Chapter 15: SQL Database Access������������������������������������������������������������������������ 437

Chapter 16: Client and Server Support����������������������������������������������������������������� 449


MIME Packages������������������������������������������������������������������������������������������������������������������������� 449
Network Packages�������������������������������������������������������������������������������������������������������������������� 449
The Net Package����������������������������������������������������������������������������������������������������������������������� 450
The HTTP Template Package����������������������������������������������������������������������������������������������������� 462
The Net.HTTP Package�������������������������������������������������������������������������������������������������������������� 467
URL Package����������������������������������������������������������������������������������������������������������������������������� 477

Chapter 17: Go Runtime���������������������������������������������������������������������������������������� 479


Errors Package�������������������������������������������������������������������������������������������������������������������������� 479
Flag Package���������������������������������������������������������������������������������������������������������������������������� 480
Log Package����������������������������������������������������������������������������������������������������������������������������� 485
Math Package��������������������������������������������������������������������������������������������������������������������������� 492

x
Table of Contents

Operating System Support Packages��������������������������������������������������������������������������������������� 507


Reflection Package������������������������������������������������������������������������������������������������������������������� 515
Regular Expression Package����������������������������������������������������������������������������������������������������� 517
Go Runtime Packages��������������������������������������������������������������������������������������������������������������� 519
String Processing Packages����������������������������������������������������������������������������������������������������� 520
Concurrency and Goroutines����������������������������������������������������������������������������������������������������� 525
Testing Package������������������������������������������������������������������������������������������������������������������������ 528
Time and Date Package������������������������������������������������������������������������������������������������������������ 533

Appendix A: Installing Go������������������������������������������������������������������������������������� 541

Appendix B: Some Go FAQs����������������������������������������������������������������������������������� 553

Appendix C: Go Gotchas to Look Out For�������������������������������������������������������������� 561

Appendix D: Mark-Sweep Pseudocode����������������������������������������������������������������� 567

Appendix E: ASCII vs. UTF-8��������������������������������������������������������������������������������� 571

Index��������������������������������������������������������������������������������������������������������������������� 575

xi
About the Author
Barry Feigenbaum, Ph.D., has decades of software engineering experience. During his
career, he has worked for major industry-leading companies, such as IBM and Amazon,
and is currently at Dell where he is a Senior Principal Software Engineer. He has worked
on mainframe and midrange servers and many applications for personal computers.
He has developed software products, such as assemblers for multiple hardware
architectures, in many key industry languages such as C/C++/C#, Python, JavaScript,
Java, and now Go. He has extensive experience in the full software development life
cycle. Most recently, he has committed himself to leading teams developing mission-­
critical microservices, most often written in Go, that operate in large clustered
environments.
He led the early development of the LAN support inside Microsoft Windows
(he defined the SMB protocol that is the basis for both the CIFS and the SAMBA
technologies). He has served as a software tester, developer, and designer as well as a
development team lead, architect, and manager on multiple occasions. He was a key
contributor as a developer, architect, and manager to several releases of PC-DOS and
OS/2. In these roles, he worked extensively with Microsoft on joint requirements, design,
and implementation.
Dr. Feigenbaum has a Ph.D. in Computer Engineering with a concentration in
object-oriented (OO) software design and other degrees in Electrical Engineering. He
has published multiple articles in technical magazines and juried journals. He has
coauthored several books on IBM PC-DOS. He has spoken at numerous technical
conferences, such as JavaOne. He has served on industry standard bodies. He has taught
multiple college-level courses on data structures, software engineering, and distributed
software as an adjunct professor at several universities. He has over 20 issued US patents.
He is married, has one son, and lives in Austin, TX.

xiii
About the Technical Reviewer
Ronald Petty, M.B.A., M.S., is founder of Minimum
Distance LLC, a management consulting firm based in
San Francisco. He spends his time helping technology-
based startups do the right thing. He is also an instructor
at UC Berkeley Extension.

xv
Acknowledgments
To my son Barry, Jr., for his careful review of the drafts of this book. He provided a
perfect example of the book’s target audience: a professional Java programmer wanting
to learn Go.
A hearty thanks to all the other reviewers that made helpful comments, suggested
additional content, and/or made errata corrections: Charles Stein, Divya Khatnar, Rosish
Shakya, and Sharath Hegde.
I especially want to thank Ronald Petty for his thorough technical review of this text.
Also, for his numerous suggested content improvements and code samples, several of
which were included.
I wish to thank Jason Isaacs at Dell who supported me during the creation of this text
and allowed me to go forward with this effort.
To the developers of Go and to the Go community in general, many thanks for
building such a powerful tool. I learned much from the extensive Go documentation and
the many articles, blogs, wikis, tutorials, and books provided by the community.

xvii
Introduction
Since its debut in the mid-1990s, Java has enjoyed huge success. Arguably more so
than other languages, Java is a major player in the web application space and key data
processing areas such as Big Data tools, among others. Among other aspects, Java’s high
level of portability across operating systems and hardware architectures, its rich and
improving over time language and library of functions, as well as its good performance
contributed to this success.
But Java comes with some drawbacks. Java was created at a time when Object-­
Oriented Programming1 was the norm and network delivery of code was advantageous.
The resulting Java runtime footprint is quite large, and it is resource intensive. The Java
developers are trying to address this to some degree with the use of Java Modules along
with standard library subsetting and the Graal2 Virtual Machine, but typical Java code,
for the same functionality, often uses more resources than typical Go code does.
As time is passing, the Java language and runtime is no longer an optimal fit for many
modern, especially cloud-based, applications. Also, the Java language is continuously
growing and can be a challenge to fully master. Go is deliberately a simple, thus easy to
master, language.
The Go language and runtime is relatively new and designed to meet the needs
of modern cloud computing systems and other system3 programming tasks. It is
considered by many to be a “better C than C” and thus a potential replacement for the C4
programming language, the language it most closely resembles. Go is also likely to take
over a large fraction of the Java server and application space. Thus, it is the raison d'etre
for this book.
Many new applications and reengineering of existing applications are now being
developed in Go. For applications previously written in Java, Kotlin5 or Scala6 JVM

1
https://en.wikipedia.org/wiki/Object-oriented_programming
2
www.graalvm.org/java/
3
Oriented to operating the computer system rather than achieving business tasks.
4
https://en.wikipedia.org/wiki/C_(programming_language)
5
https://kotlinlang.org/
6
www.scala-lang.org/

xix
Introduction

(both available as Java Virtual Machine–based languages) might be the more expected
language to use, but often Go is winning out over them. As an example of a redo into
Go, Khan Academy7 is using Go to reengineer8 its previous Python site implementation.
This often happens because Go exhibits many of the ease-of-use features common to
scripting languages with the efficiency of compiled languages.
The original Go lead designers, Robert Griesemer, Rob Pike, and Ken Thompson, all
at Google, wanted to define a language and associated runtime with these key features
(some also provided by Java):
• High developer productivity – Go offers a consumable and
reasonably complete runtime. It also offers a one-stop shopping
toolchain. It has widespread high community support.

• High readability and developer usability – The language itself is


small, so it is easy to learn, and its code is both easy to read and
understand vs. easiest/fastest to write. It has a targeted ease of use
comparable to nonstatically typed languages like Python. Often, the
language is opinionated (sort of take it or leave it).

• Go uses memory garbage collection (GC) which reduces programmer


effort and makes for more reliable programs.

• Go is statically linked (vs. dynamically linked, as Java is); this makes it


easier to manage deployment and execution of Go programs.

• Static typing – Generally supports safer, more performant, and more


predictable programs; helps with high reliability and long duration
execution critical for servers.

• Runtime efficiency – The code efficiently uses the processors it runs


on, comparable to what is achievable in C/C++9 applications.

7
www.khanacademy.org/
8
https://blog.khanacademy.org/half-a-million-lines-of-go/
9
https://en.wikipedia.org/wiki/C%2B%2B

xx
Introduction

• High network performance – Distributed/cloud use cases are now


common, and the code needs to be performant for them. For the
same level of function, Go is often less resource intensive than
Java typically is; this helps with reducing resource footprint and
improving scale in modern cloud distributions.
• High utilization of multi-processor systems – The code needs to allow
easy and safe exploitation of multi-processor (core) systems that have
become the norm. Go excels at this.
Robert Pike summarized10 this as follows:
… we wanted a language with the safety and performance of statically
compiled languages such as C++ and Java, but the lightness and fun of
dynamically typed interpreted languages such as Python. It was also impor-
tant that the result be suitable for large systems software development on
modern, networked, multicore hardware.
The Go Brand Book11 (GBB) states:
Go is an open source programming language that enables the production
of simple, efficient and reliable software at scale.
The GBB further states that Go has these benefits for new programmers:
Developer productivity of a dynamic language with the speed,
safety, and reliability of a static language
• Easy to learn & readable
• Has a vibrant, welcoming community, spanning open-source
developers, startups, large companies, and universities
• The language for the Cloud
And these benefits for experienced programmers:
• Solves big engineering problems
• Backed by Google, who understands and supports needs specific to
open source communities and Go
• High demand for Go programmers

10
www.red-gate.com/simple-talk/opinion/geek-of-the-week/rob-pike-geek-of-the-week/
11
https://storage.googleapis.com/golang-assets/Go-brand-book-v1.9.5.pdf
xxi
Introduction

In many ways, Go is a lot like Node.js,12 a popular JavaScript13-based application


development platform. Node.js makes it easy to develop lightweight servers very
quickly and thus is popular as a microservices platform. Node.js and Go have
similar capabilities, history, and community support. Go, because of its type safety
and goroutines (vs. Node.js’s event loop), is likely to be able to provide more
scaled and reliable solutions than Node.js can. In the author’s opinion, Go will also
consume a significant number of the Node.js use cases.

As a result, many applications previously done in Java can instead be implemented


in Go with some advantages, especially in cloud environments.
So, in summary, here are some Go advantages relative to Java:

• Go is a smaller language that is clean, maintainable, and easy to


learn.

• Go is better suited to support multi-core processors and high levels of


concurrency.

• Go has a smaller but strong set of standard libraries, especially for


building servers, that comes bundled with the standard installation.

• Go is well suited to cloud execution, especially in a containerized


environment.

• Go is well suited to any constrained environments where large code


and runtime footprint can be issues.
Go is open source, has an active developer community, and is sponsored by Google;
it will not go away. Future Go evolution will retain backward compatibility;14 this is a Go
community promise. This makes Go a great language for commercial development.
Hackernoon15 says: “Go is on a trajectory to become the next enterprise programming
language.”

12
https://en.wikipedia.org/wiki/Node.js, https://nodejs.org/en/
13
https://en.wikipedia.org/wiki/JavaScript
14
https://golang.org/doc/go1compat
15
https://hackernoon.com/go-is-on-a-trajectory-to-become-the-next-enterprise-
programming-language-3b75d70544e

xxii
Introduction

They further say:

Go — a programming language designed for large-scale software develop-


ment — provides a robust development experience and avoids many issues
that existing programming languages have. These factors make it one of the
most likely candidates to succeed Java as the dominating enterprise soft-
ware platform in the future. … Taken as a whole, they (Go’s design choices)
position Go as an excellent choice for large development projects looking
for a modern programming language beyond Java.
InfoWorld16 says:

Google’s Go programming language has certainly made a name for itself.


Lightweight and quick to compile, Go has stirred significant interest due to
its generous libraries and abstractions that ease the development of concur-
rent and distributed (read: cloud) applications. … But the true measure of
success of any programming language is the projects that developers create
with it. Go has proven itself as a first choice for fast development of network
services, software infrastructure projects, and compact and powerful tools
of all kinds.
Open source projects they mention that use Go include Docker, Kubernetes, Fedora
CoreOS, InfluxDB, Istio, Traefik, Hugo, Terraform, CockroachDB, and Gravitational
Teleport.
Note that Docker and Kubernetes are the foundation technologies for the
containerization of many modern applications. Many organizations depend on them to
be rock solid and performant. This is a testament to the maturity of the Go language and
its runtime.
Brainhub17 list some major companies using Go and the advantages they see:
• Simple code

• Created for large projects

• Easy to learn

• One problem – one solution

• Ease of maintenance

16
www.infoworld.com/article/3442978/10-open-source-projects-proving-the-power-of-
google-go.html
17
https://brainhub.eu/library/companies-using-golang/

xxiii
Introduction

• Similar to C

• Designed for multi-core processors

• Designed for the Internet

• Quick compilation

• Small application size

• Open source model


They mention companies using Go including Google (of course), Uber, Twitch,
Dailymotion, SendGrid, Dropbox, and SoundCloud.
Awesome Open Source18 lists over 15,000 (and growing) projects that use Go.
Sandra Parker19 projects20 Go has a winning future where she emphasizes: “Because
it is made by Google.”
She indicates why it’s currently popular: “Go is different from other languages. It is
young but so powerful that it was able to bring up geek’s engagement from the very start.”
In summary:

• It is convenient, fast, and secure to write code with Golang, and it


provides cross-platform support…

• Google cares about the user.

• Golang has cloud infrastructure.

• Google has money.

And why it is going to get more popular as time passes:


Applications written on Go are highly performant. Golang is very efficient
like C/C++, handling parallelisms like Java, and has easy code readability
like Python, Perl, and Erlang. … This is why many companies migrate to
Golang from other languages. Golang is the future.

18
https://awesomeopensource.com/projects/go
19
www.quora.com/profile/Sandra-Parker-34
20
https://medium.com/@Sandra_Parker/why-golang-is-the-future-part-1-ed7dd4f419d and
https://medium.com/@Sandra_Parker/why-golang-is-the-future-part-2-1f984ae8f1a4

xxiv
Introduction

In 2020, Ziff Davis21 showed that Go is the most desired new language to learn, as
shown in Figure 1.

Programming languages that working professionals would like to learn:

40% Working professionals

32%

30%

25%
24%
21%
20%
20%
18%
16%
15%
15% 14%

10%

5%

0%

Go Python Kotlin Javascript Bash/Shell Typescript Scala R (Rscript)


(Node.js) /PowerShell

Figure 1. Programming languages professionals want to learn

Other sources extol the virtues of Go and indicate it has a growing future. For
example, Towards Data Science22 states these as key features for Go’s success:
1. Go has language-level support for Concurrency. It offers a CSP23
based message-passing concurrency via Goroutine (lightweight
Green thread) and Channel.

21
https://en.wikipedia.org/wiki/Ziff_Davis, www.zdnet.com/article/developers-
say-googles-­go-is-most-sought-after-programming-language-of-2020/, and www.
hackerearth.com/recruit/developer-survey/
22
https://towardsdatascience.com/top-10-in-demand-programming-languages-to-learn-
in-2020-4462eb7d8d3e
23
Communicating sequential processes – https://en.wikipedia.org/wiki/
Communicating_sequential_processes

xxv
Introduction

2. The biggest USP24 of Go is its language design and simplicity. It has


successfully combined the simplicity and productivity of Python
and the power of C.

3. Go has embedded Garbage Collector (albeit not as mature as JVM


garbage collector). Go developers can write system programming
with the safety of Java, Python.

Go is ranked as one of the top five most loved languages by GeeksforGeeks,25 which
describes Go as follows:
Go is a statically typed, open-source programming language designed at
Google that makes programmers more productive and helps to build simple,
reliable, and efficient software very easily. This language … is syntactically
similar to C, but with memory safety, garbage collection, structural typing,
and CSP-style concurrency. Go is well known for its high-performance in
networking and multiprocessing.
They cite these key virtues:

1. Concurrency: provides greater concurrency with the help of


goroutine which makes it extremely easy to implement in a
concurrent system. …

2. Simplicity and Consistency: This language was designed with a


very minimalistic approach and it is well known for its simplicity.
… The standard library and the packages are consistent.

3. Object-oriented: Go is an Object-oriented programming language


and supports the useful features of OOPs. …

4. Tools: Go provides many useful tools for building, testing, and


analyzing code…

5. Compiler: Its compiler is super-fast and easily compiles a large go


program within a few seconds. …

24
Unique selling proposition – https://en.wikipedia.org/wiki/Unique_selling_proposition
25
www.geeksforgeeks.org/top-5-most-loved-programming-languages-in-2020/

xxvi
Introduction

Note that this author disagrees with point 3. In his opinion, Go is object-based,26 not
object-oriented.
The popular TIOBE27 index shows that Go use is growing at a fast rate. A late 2020
survey shows this:

• Current Year Rank: 13

• Previous Year Rank: 20

• Growth Rate: High

Few languages have seen such high year-over-year growth. TIOBE twice named
Go as the “language of the year.” The future need for Go programmers is expected to
continue to grow rapidly.
A look at Go Users28 shows hundreds of organizations, including some of the world’s
largest companies, using Go around the world. This list is likely to omit many actual
users.
Go is used, and in many ways proven effective, in many complex programs. The
Docker29 container system and the Kubernetes30 container orchestrator are prime
examples of industry-leading programs written in Go. Also, the Go compiler, builder,
and most of the standard libraries are written in Go.31 They are an important test case in
themselves.
In 2020, StackOverflow has ranked (https://insights.stackoverflow.com/
survey/2020) the most loved languages. Go is among the top of the top 25 listed well-known
languages, and it ranks higher in that list on the desired (“loved”) scale than Java. Note how
well it compares to Python; this is remarkable for a compiled language.

26
https://en.wikipedia.org/wiki/Object-based_language
27
The Importance of Being Earnest – https://en.wikipedia.org/wiki/TIOBE_index
28
https://github.com/golang/go/wiki/GoUsers
29
www.docker.com/
30
https://kubernetes.io/
31
Originally bootstrapped from a C version of these tools.

xxvii
Introduction

Table 1. Most Loved Languages Survey


Language Loved Percentage (Using and Want
to Continue Using)

Rust 86.1%
TypeScript 67.1%
Python 66.7%
Kotlin 62.9%
Go 62.3%
Julia 62.2%
Dart 62.1%
C# 59.7%
Swift 59.5%
JavaScript 58.3%
SQL 56.6%
Bash/Shell/PowerShell 53.7%
HTML/CSS 53.5%
Scala 53.2%
Haskell 51.7%
R 44.5%
Java 44.1%
C++ 43.4%
Ruby 42.9%
PHP 37.3%
C 33.1%
Assembly 29.4%
Perl 28.6%
Objective-C 23.4%
VBA 19.6%

xxviii
Introduction

All this should make learning to program in Go highly interesting to experienced Java
developers looking to broaden their skills and marketability. In the author’s opinion, Go
will emerge as the go-to language for multi-core computing over networks, especially for
servers.
Of course, for a complete analysis, we need to contrast the mascots of Go and Java.
In the author’s opinion, Go’s mascot is both simpler and cuddlier, as, arguably, is the
language itself.
Figure 2 shows the Go logo and Gopher mascot. 32

Figure 2. Go mascot and logo32

Figure 3 shows the Java mascot (Duke).33

Figure 3. Java mascot33

32
The Go gopher was designed by Renee French. (http://reneefrench.blogspot.com/) and is
licensed under the Creative Commons 3.0 Attributions license.
33
https://wiki.openjdk.java.net/display/duke/Main

xxix
Introduction

Gophers, welcome aboard! In this book, we will briefly explore the concepts behind
Go and why it was created. This overview will be followed by an introduction to Go’s
various features and a look at if/how they differ from Java. Then comes a presentation
of most of the Go language statements and data types. This is followed by a brief look
at some potential future Go enhancements. A capstone example Go program is then
presented to unify the Go experience. Next comes a review of the Go standard libraries
as they compare to similar Java libraries. Finally comes a survey of a subset of the various
Go standard libraries as an introduction to their usage. Deeper and more comprehensive
descriptions are available at the Go site.
More precisely, this book’s content is broken down into three parts with several
chapters within each part.
Some background on Go:

• A brief look at Go vs. Java comparing key features of both languages

• Summary of features Java has that Go does not have

A description of the Go language and its key features with a look at using Go in
practice:

• A brief side-by-side comparison of Go features with Java

• A survey of Go key features

• A more detailed view of important Go characteristics (like Go


keywords, etc.)

• A detailed view of Go data types


• A discussion of Go’s error reporting mechanism

• A broader discussion on Go’s interface data type and how it is applied

• A description of each Go statement

• A more detailed discussion on applying Go data types

• A look at testing Go vs. Java programs

• A brief look at possible future Go enhancements

• A capstone program illustrating many Go and Go library features

xxx
Introduction

An introduction to the Go standard libraries in comparison with Java libraries


combined with a survey of key Go standard libraries:

• A discussion of key Java library packages with similar Go packages.

• A brief side-by-side comparison of commonly used Java methods


with similar Go functions.

• A brief discussion of formatting data values in Go.

• A brief discussion of file input/output in Go.

• This part includes chapters covering compression/decompression,


image processing, input/output, cryptography, relational database
access, network access, and Go runtime access.

• It is intended to bring awareness of the various Go libraries and not a


complete understanding of all the available functions.

• This is the largest part of the book.

In addition, there are five appendixes with supplementary information such as how
to install Go, as well as some summary and reference information.

Note In some of the code examples in this book, long source lines are wrapped
into multiple lines. This wrapping may not be allowed in actual Go source.

The source for the capstone programs, as well as for some of the other listing
samples in this book, is available at the book website: www.github.com/apress/
go-­for-java-­programmers.
Before we dive into Go, let us consider why Go exists. Rob Pike summarized34 the
language and why it was created this way:
The Go programming language was conceived in late 2007 as an answer
to some of the problems we were seeing developing software infrastruc-
ture at Google. The computing landscape today is almost unrelated to
the environment in which the languages being used, mostly C++, Java,
and Python, had been created. The problems introduced by multicore

34
https://talks.golang.org/2012/splash.article

xxxi
Introduction

processors, networked systems, massive computation clusters, and


the web programming model were being worked around rather than
addressed head-on. Moreover, the scale has changed: today's server
programs comprise tens of millions of lines of code, are worked on
by hundreds or even thousands of programmers, and are updated
literally every day. To make matters worse, build times, even on large
compilation clusters, have stretched to many minutes, even hours.

Go was designed and developed to make working in this environment


more productive. Besides its better-known aspects such as built-in concur-
rency and garbage collection, Go's design considerations include rigorous
dependency management, the adaptability of software architecture as sys-
tems grow, and robustness across the boundaries between components.
Go is a compiled, concurrent, garbage-collected, statically typed
language developed at Google. It is an open source project: Google imports
the public repository rather than the other way around.
Go is efficient, scalable, and productive. Some programmers find it fun
to work in; others find it unimaginative, even boring. In this article we will
explain why those are not contradictory positions. Go was designed to
address the problems faced in software development at Google, which led
to a language that is not a breakthrough research language but is nonethe-
less an excellent tool for engineering large software projects.
Wikipedia35 defines Go as follows: “Go is a statically typed, compiled programming
language…. Go is syntactically similar to C, but with memory safety, garbage collection,
structural typing, and CSP-style concurrency.”
Wikipedia36 describes Java as follows:
Java is a class-based, object-oriented programming language …. It is a gen-
eral-purpose programming language intended to let application developers
write once, run anywhere (WORA), meaning that compiled Java code can
run on all platforms that support Java without the need for recompilation.
The syntax of Java is similar to C and C++, but has fewer low-level facilities
than either of them. The Java runtime provides dynamic capabilities (such
as reflection and runtime code modification) that are typically not available
in traditional compiled languages.

35
https://en.wikipedia.org/wiki/Go_(programming_language)
36
https://en.wikipedia.org/wiki/Java_(programming_language)

xxxii
Introduction

These descriptions cover some of the key similarities and differences. In the
author’s opinion, the relative brevity of the Go description reflects the relative
simplicity of Go vs. Java.
Go addresses the needs of modern system and application software development in
cloud environments on modern multi-core machines. In the author’s opinion, it meets
these goals very well. As you explore Go more within these pages, you will see its features
and functions and how they match and support the goals stated earlier. By the time you
finish this book, perhaps you will also agree.
Go was not designed to replace (cover all use cases of ) Java. It is more targeted
toward the use cases of the C (and to some extent C++) language. It is primarily a system
programming language well suited toward implementing servers and tools such as
compilers. Java also supports these types of programs.
One of the reasons Go is popular is it is lightweight relative to many other languages.
Go is arguably more lightweight than Java in many areas. This is one of its most attractive
attributes.
Go’s threading model, provided by goroutines and channels, certainly is lighter
weight. Because it lacks Object-Oriented Programming (OOP) features, its data model
and error processing are also more lightweight. Even more lightweight is the set of
standard libraries. Perhaps most critically, Go’s single executable (vs. a JRE and many
JARs) deployments and resulting fast program launching are most attractive.
Go is also arguably easier to master than Java. The language is simpler and has fewer
constructs to learn. The runtime libraries are, while functional, generally more basic and
approachable.
This is not to say that Go is necessarily better than Java (or the reverse), but that
it is often more approachable and easier to master and use. Both languages and their
runtimes will extend over time; Go is more likely to continue its more approachable style.

xxxiii
Assessments
Divya Khatnar: If one knows Java, they will surely enjoy learning Go using this book. The
author makes sure that each topic uses Java as a baseline to explain Go. Not only does this
book teach you Go, but it also sharpens your understanding about Java.
Charles Stein: As Go becomes a staple language, Java users need a clear guide to help
them make the transition. This book thoroughly covers the basics and exciting applications
of Go from a Java-analogous perspective.
Sharath Hedge: This book covers all the comparisons of Java and Go exhaustively.
Also, it covers important packages provided by Go. As a developer if I want to start a
project in Go, this book will offer ready reckoner for the many questions I have. This book
offers examples for the majority of the cases, which helps a lot.

xxxv
PART I

First Look at Go
Welcome, future Gophers! Prepare for a journey of discovery and enrichment.
This is a book to help you learn the Go (aka Golang1) programming language
and many of the Go standard libraries in order to become successful Gophers. This
text assumes no prior knowledge of Go and is oriented for use by experienced Java
programmers. This book is generally organized using a comparison between Java
features and if/how these similar features exist in Go.
This book assumes the reader knows Java already; it is not a Java tutorial. This book
also assumes the reader has basic competence in fundamental programming concepts
and procedural programming techniques.
As it is generally the case for any programming language, it is nearly impossible to
introduce language topics/features in a strictly linear order (all topics fully described
before any are used). Most languages interdepend on their features in such a way as
to make this impossible. Go is no exception; in fact, such interdependence between
features is a key Go design aspect.
This book does not achieve such a perfect topic order. Topics will sometimes be
mentioned before they are fully described. Some background information will be
provided at the point of reference, but it may sometimes be necessary to jump ahead
to scan the more detailed presentations that come later. This ordering can result in
limited repetition of content throughout the book. Limited repetition is also employed
throughout the text to help reinforce key concepts.
Learning by comparison and by example are powerful and effective techniques.
In this book, we will be comparing Go and some of its standard libraries to Java and
some of its standard libraries to teach basic Go programming. The book will often use
examples to illustrate both similarities and differences. This is the major purpose of this
book.

1
As apart from the Go game and other uses. Also, the official website: www.golang.org
Part I First Look at Go

This book will not cover every detail or option of the Go language, but most of its
features are described or at least shown in examples. Certainly, Go will be described
at a useful level of detail. The Go Language Specification can be used to get a full and
complete description. The same goes for many of the standard Go libraries.
Most references and comparisons will be against Java. But, as the Go language and
runtime are targeted strongly to the use cases of the C language and the C standard
library, this book will also compare Go to C at times. Since C++ is a derivative and
superset of C, at times this book may compare Go to C++ as well. In no case will
knowledge of either C or C++ be a prerequisite to use this book effectively. Occasionally,
this book will compare Go to other languages.
While typically what the term “Go” means, Go is more than a language, a set of
runtime libraries, and a set of developer tools. “Go” also represents a community of
users and contributors. Like with Java, the community is a rich source of functions
beyond the standard Go capabilities as well as a vast source of training and support for
Go developers. Many of these extensions are easily accessible via the Go toolchain and
repositories such as GitHub.
Go was first announced in November 2009. Release 1.0 came in September 2012.
Prior to version 1.0, the language and runtime changed often, sometimes incompatibly.
Post 1.0, there is much more stability.
Each release after 1.0 has a goal of complete backward compatibility (all older source
programs continue to compile and run after being rebuilt), but there have been a few
exceptions. The change in the default for GO111MODULE environment option from
auto to on in Go 1.16 is an example. Such version-to-version incompatibilities are rapidly
reducing over time.
As of the date of this book’s publication, Go has had more than a dozen major
(XX of 1.XX) releases and numerous point (yy of 1.XX.yy) releases. Each major release
introduces new tools, language and/or library features, performance improvements, and
often bug fixes. Detailing them in a book is a form of planned obsolescence and thus
will not be done. A detailed summary can be found at https://golang.org/doc/devel/
release.html.
Before we begin learning Go, we will first look at some key features of the Java
language that Go does not provide. On the surface, this may make Go look inferior
compared to Java, but as you go further into the text, the author believes you will see that
this is not the case.

2
Part I First Look at Go

The first part of this text has a few samples of Go code; it is mostly background
information. That will change in the subsequent parts of this text.
Note in the text, especially in the capstone sections, source file names are
mentioned. Often, these names are not the literal operating system file names but may
be shown in different cases. Some operating systems require file names to be entered in
their exact case, and others do not.

3
CHAPTER 1

A Brief Look at
Go vs. Java
There are many obvious and subtle differences between Java and Go. They can be
compared as a language and as a runtime. This survey concentrates mostly on a
language comparison. It is intended to present a broad-stroke comparison. Much deeper
comparisons are done throughout the text.
Some of the text in this chapter might be read as disparaging Go. That is not the
intent. Go is a powerful language, and it can easily hold its own against Java. But Java
does have features Go does not, and they will be summarized later.
Note the descriptions here can require deeper knowledge of Go that has been
presented so far for a full understanding. You may want to revisit this chapter after
becoming more familiar with Go later in this text.
The Go language and its associated runtime have both many similarities and many
differences from the Java language and its associated Java Runtime Environment (JRE).
This chapter will attempt to summarize them at a high level. These similarities and
differences will be discussed in greater detail later in this text.
Both Go and Java are Turing-complete1 environments, which means (almost) any
possible program can be written in either of them. It is just a matter of the relative
development effort expended and the resulting program size and performance.
It should be noted that the Go language and the Go development experience more
closely matches that of C than it does of Java. The style and semantics of the Go language
more closely resemble that of C than Java. The standard Go libraries also more closely
resemble those that come with C.

1
Alan Turing described a universal computing engine, now called a Turing Machine, that can
compute any possible calculation. Any programming language that can be used to author a
Turing Machine is referred to as “Turing Complete.”

5
© Barry Feigenbaum 2022
B. Feigenbaum, Go for Java Programmers, https://doi.org/10.1007/978-1-4842-7199-5_1
Chapter 1 A Brief Look at Go vs. Java

One exception with the comparison to C is that of the Go program building


experience. In C, this is typically driven by the Make2 (or a variant) utility. In Go, it is
driven by the Go builder tool. In the author’s opinion, the Go approach is superior and
easier to use (no make files are needed).
Note some Go developers use make file–like approaches, especially in complex
projects that have more than just Go source files as components and thus need other
artifacts to also be constructed. Make files are often used to script multistep processes
beyond what the Go builder can do. This is similar to using Ant3 or Maven4 in Java.

 o Is a Compiled (vs. Interpreted, As Java Is)


G
Language
Like C and C++, Go programs are completely built before execution begins. All source is
compiled into the machine language of the target computer architecture. Also, all code
is compiled to the target operating system. In contrast, Java is compiled into a virtual
machine language (aka bytecode), and that is interpreted by the Java Virtual Machine
(JVM). For improved performance, that bytecode is often compiled into machine
language dynamically at runtime. The JVM itself is built for a particular operating system
and hardware architecture.
Once built, Go programs require only an operating system to run them. Java
programs require, in addition, that a JRE (of the required version) exist on the computer
before they can be run. Many Java programs may also require additional third-party code
to be present.
The Go approach often results in faster program startup and a more self-contained
program, both of which make it more suitable for containerized deployments.

2
https://en.wikipedia.org/wiki/Make_(software)
3
https://en.wikipedia.org/wiki/Apache_Ant
4
https://en.wikipedia.org/wiki/Apache_Maven

6
Chapter 1 A Brief Look at Go vs. Java

Go and Java Share Similar Program Structure


Both languages support the notion of data structures that contain methods and fields.
In Go, they are called Structs, while in Java they are called Classes. These structures are
collected into groupings called Packages. In both languages, packages can be arranged
hierarchically (i.e., have nested packages).
Java packages contain only type declarations. Go packages can contain base
declarations like variables, constants, functions, as well as derived type declarations.
Both languages access code in different packages by importing it. In Java, imported
types can be optionally used unqualified (String vs. java.lang.String). In Go, all
imported names must always be qualified.

 o and Java Have Some Code Style Differences


G
That Influence How Code Is Structured
• Java declarations put the type first, while in Go the type comes last.
For example:

Java – int x, y z;

Go – var x, y, z int

• Java methods can return only a single value. Go functions can return
many values.

• Java methods and fields must be declared inside the type that they
belong to. Go methods are defined outside the owning type. Go
supports functions and variables that are independent of any type.
Java has no true static shared variables; static fields are just fields of
some class (vs. an instance). Go supports true static (global) variables
that are allocated in the executable image.

• Go has full closures (can capture mutable data), while Java only
supports partial closures (can capture only immutable data). This can
make first-class functions in Go more powerful.

7
Chapter 1 A Brief Look at Go vs. Java

• Go lacks user-defined generic types. Some built-in types


(e.g., slices and maps) are generic. Java supports generic types
of any reference type.

Note there is an approved proposal to add generic types to Go in


the future.

• Java allows type extension of only other types (classes, enums,


and interfaces), while Go can base new types on any existing type,
including primitive types (such as integers and floats) and other user-­
defined types. Go can support methods on any of these custom types.

• Go and Java interfaces work very differently. In Java, a class (or enum)
must explicitly implement an interface if it is used (methods called)
through that interface. In Go, any type can implement an interface
simply by implementing the methods of that interface; no declaration
of intent to implement the interface is needed, it just happens as a
side effect of the methods being present. Many standard (inherited)
behaviors in Java (such as the toString() method) are provided in
Go by a type implementing a common interface (equivalently the
String() method of the Stringer interface).

Both Go and Java Are Procedural Languages


Imperative programs are those that work by explicitly changing state over time and
testing that state. They are a direct reflection of the ubiquitous von Neumann5 computer
architecture. Procedural programs are imperative programs that are composed of
procedures (aka functions in Go and methods in Java). Each language provides the
following key capabilities of procedural languages:

• Can execute an expression, often with an assignment to a variable.

• Can execute a sequence (0+) of statements (often called a


basic block).

• Often also a single statement can implicitly act as a block.

5
https://en.wikipedia.org/wiki/Von_Neumann_architecture

8
Chapter 1 A Brief Look at Go vs. Java

• Can make one-way (if), two-way (if/else), or n-way (if/else if/


else, switch) conditional branches in code flow.

• Can loop over statements.

• Java has while, do, and for statements; Go combines them all into
just for.

• Can define reusable code that can be invoked from


multiple locations.

• Java has methods; Go has functions, some of which are methods.

All6 programs can be written using only these constructs.

J ava Is an Object-Oriented (OO) Language, While


Go Is Not Fully OO
As is true of all OO languages, Java is a class-based language. All code (methods) and
data (fields) are encapsulated in some class implementation. Java classes support
inheritance in that they can extend a super-class (starting at Object). Go allows
composition (a struct can be embedded in another struct) that can often get some of the
code reuse benefits of inheritance, but not all.
Java provides full control over the encapsulation (through visibility: public/
protected/package private/private) of methods and fields. Go does not provide all these
options. Go structs are like classes in how they have fields and can have associated
methods, but they do not support subclassing. Also, Go only supports the equivalent of
public and package private visibilities.
In Java, both classes and interfaces support polymorphic method dispatch. In Go,
only interfaces do polymorphic method dispatch. Go has no equivalent of an abstract
base class. Again, composition can provide a subset of this feature.
Note Java, while generally considered to be OO, is not a perfect example of the OO
style of programming. For example, it has primitive data types. But this text is not about
being critical of Java’s design.

6
https://en.wikipedia.org/wiki/Structured_programming#Elements

9
Chapter 1 A Brief Look at Go vs. Java

Java Is a Highly Functional Language, Go Is Less So


Java, since version 8, has well supported functional programming (FP). FP is
programming with only functions that have local data; no global and mutable state
exists. Java supports the ability to create first-class function literals (called Lambdas)
and pass them to other code to be invoked. Java also allows external (or explicit) looping
(while, for, etc.) to be replaced by internal looping (inside methods). For example, the
Java Streams support provides this.
Go also has first-class function literals, but it lacks similar support for internal
looping; looping is typically external. First-class functions supply lambda-like functions,
often in a superior way. The lack of internal looping is considered a virtue in Go as it
produces more obvious code.
Java FP support strongly depends on generic types. Currently, Go lacks these.

J ava Is a Highly Declarative Language, Go Is


Less So
Through a combination of Annotations and features such as Streams, Java code can
be written in a declarative style. This means the code says what is to be done, but not
explicitly how it is to be done. The runtime converts the declarations into behaviors that
achieve the intended results. Go does not promote an equivalent style of programming;
code must be written to explicitly say how to achieve a behavior. As a result, Go code is
more obvious but sometimes larger and more repetitive than typical Java code is.

Many Java Features Are Annotation Driven


Many Java libraries (especially those called frameworks), such as Spring, make strong use
of Java’s Annotations. The annotations provide metadata, typically consumed at runtime,
to modify the behaviors provided by the libraries. Go does not have annotations, so
this capability is missing. As a result, Go code is often more explicit; this is generally
considered a virtue. Go can use code generation to get similar results to annotations. Go
does have a simple form of annotation, called a tag, that can be used to customize some
library behavior, such as JSON or XML formatting.

10
Chapter 1 A Brief Look at Go vs. Java

The use of annotations can bind configuration decisions to the source code.
Sometimes, this is a disadvantage as the decision needs to be delayed until runtime.
When this is so, Go and Java often use similar approaches (such as command-line or
configuration file parameters).

Go Does Not Support Exceptions


Java has Exceptions (really Throwables which are Exceptions or Errors) that can be raised
to report unusual conditions. Exception usage is widespread in Java and often used to
report both predictable and unpredictable failures. Error returns as values from methods
are rare.
Go makes a stronger separation of these roles. All failures are reported by function
return values that a caller must explicitly test for. This works well because Go functions
can more easily return multiple values, such as a result and an error.
Go has Panics that have a similar role as Java Errors. They are raised much less
frequently. Unlike in Java, panic values are not a hierarchy of types, just a wrapper on
a value of the developer’s choice, but often an instance of the error type. One never
declares the type of a panic value that a function can raise (i.e., there is no equivalent to
Java’s throws clause). This often means less verbose code. Much Java code follows this
pattern by only throwing instances of RuntimeException that do not need to be declared.

 oth Java and Go Use Managed Memory (Garbage


B
Collectors)
Both languages use a stack and a heap to hold data. The stack is mostly used for function
local variables, the heap for other dynamically created data. In Java, all objects are
allocated on the heap. In Go, only data that can be used beyond the lifetime of a function
are allocated on the heap. In both Java and Go, the heap is garbage collected; heap
objects are explicitly allocated by code but are always reclaimed by the garbage collector.
Java has no notion of pointers to an object, only references to objects located in the
heap. Go allows a pointer (or address of ) to any data value to be accessed. In most cases,
Go’s pointers can be used like Java references.
Go’s implementation of garbage collection is simpler than Java’s. Unlike with Java,
there are a few options available to tune it, it just works.

11
Chapter 1 A Brief Look at Go vs. Java

 o and Java Both Support Concurrency


G
but in Different Ways
Java has the notion of Threads, which are paths of execution provided by libraries.
Go has the notion of Goroutines (GRs), which are paths of execution provided by the
language itself. GRs can be looked at as lightweight threads. The Go runtime can support
using many more (many 1000s) GRs than the JRE can support threads.
Java supports synchronization controls in the language. Go has library functions
that are similar. Both Go and Java support the notion of atomic values that can safely be
updated across threads/GRs. Both support explicit locking libraries.
Go offers the notion of Communicating Sequential Processes (CSP) as a major way for
GRs to interact without explicit synchronization and locking. Instead, GRs communicate
over Channels which are effectively pipes (FIFO queues) combined with the select
statement to query them.
There are other differences in concurrency approaches that will be discussed later
in this text. GRs and threads are typically managed in different ways, as is passing state
between them.

Go’s Runtime Is Simpler Than the JRE


Go has a much smaller runtime than that provided by the JRE. There is no JVM
equivalent, but similar components, such as a garbage collection, exist in both. Go has
no bytecode interpreter.
Go has a large set of standard libraries. The Go community provides many more. But
the Java standard and community libraries arguably far exceed the current Go libraries
in both breadth and depth of function. Still the Go libraries are rich enough to develop
many useful applications, especially application servers.
All used libraries (and nothing more) are embedded into the Go executable.
The executable is everything needed to run the program. Java libraries are loaded
dynamically upon first use. This makes Go program binaries (as files) generally larger
than Java binaries (a single “main” class), but when the JVM and all dependent classes
are loaded, the total memory footprint of Java is often larger.

12
Chapter 1 A Brief Look at Go vs. Java

As Java is interpreted, it is possible to dynamically create bytecode and then


execute it. This can be done by writing the bytecode at runtime or dynamically loading
prewritten bytecode (i.e., classes). This brings great flexibility. Go, being prebuilt, cannot
do this.

The Go Program Build Process Is Different


Java programs are an amalgamation of classes, often from multiple sources (vendors),
that are constructed at runtime. This makes Java programs very flexible, especially when
downloaded across a network, a prime Java use case. Go programs are built statically
and in advance of execution. All code is available in the executable image at startup. This
provides greater integrity and predictability at the cost of some flexibility. This makes Go
more suitable for containerized deployments.
Go programs are typically built by the “go builder” which is a tool that combines a
compiler, a dependency manager, a linker, and an executable builder tool, among others.
It is included with the standard Go installation. Java classes are compiled separately
(by the javac tool, provided with a Java Development Kit (JDK)) and are then often
assembled into archives (JAR/WAR) that hold related classes. Programs are loaded
from one or more of these archives. The creation of archives, especially including any
dependencies, is generally done by programs (e.g., Maven) available independently from
the standard JRE.

Go and Java Have Similar Release Cycles


Go has adopted a biannual release cycle7 for 1.xx releases. It is best summarized in
Figure 1-1 (from the Go site).

7
https://github.com/golang/go/wiki/Go-Release-Cycle

13
Chapter 1 A Brief Look at Go vs. Java

Nov-Jan
Development Freeze

RC1 Release
Beta Release Final Release

Dec

Jan
No
v b
Fe
Feb-Apr
Oct Development
Mar
Work

Apr
Aug-Oct Sep
Development
Work g

Ma
Au

y
Jun
Jul
Final Release Beta Release
RC1 Release

May-Jul
Development Freeze

Figure 1-1. Go biannual release cycle

The Go team supports the last two releases.


Java has adopted a similar biannual cycle8 for 1.xx releases. Java has an additional
notion of Long-Term Support (LTS) releases. Non-LTS releases are supported until the
next release (LTS or not) is offered; LTS releases are supported at least until the next LTS
is offered. LTS often come every 18–24 months. Java also has the notion of experimental
features that are released but subject to change (or withdrawal) in future releases; they
provide previews of future support. Go has less of this, but, for example, the generic type
feature is being previewed in a similar way.

8
https://dzone.com/articles/welcoming-the-new-era-of-java

14
CHAPTER 2

What Java Has That


Go Does Not
Java has some features Go does not and vice versa. So, before we look at the Java features
that have some equivalent in Go, let us look briefly at the ones Go does not have. Not
every possible feature Java has that Go does not have can be listed, but some key ones
are summarized in the following.
Note that many of the Go “missing” features were omitted deliberately to keep the
language simple and efficient, not because they were hard to provide. This is considered
a virtue.

M
 ultiple Assignments
Java can assign multiple variables to the same value in a single statement. For example:

int x, y, z;
x = y = z = 10;

The closest Go can do is

var x, y, z int = 10, 10, 10

In Go, the assigned types and values can be different.

S
 tatements and Operators
Go and Java operators have different precedence. Go has fewer, and in the author’s
opinion, more natural precedence levels. When in doubt, use parentheses around an
expression to be sure.

15
© Barry Feigenbaum 2022
B. Feigenbaum, Go for Java Programmers, https://doi.org/10.1007/978-1-4842-7199-5_2
Chapter 2 What Java Has That Go Does Not

A key difference is that in Go x++ (means: x = x + 1) and x-- (means: x = x - 1) are


statements, not operators. And there is no --x or ++x expressions at all.
Go does not support Ternary Expressions. The use of the if/else statement is required.
For example, the Java expression, which gets the larger value

var z = x > y ? x : y;

needs to be something like the following in Go:

var z = y
if x > y {
   z = x
}

which is similar but not the same. You can also do something like this:

var z int
if x > y { z = <some expensive int expression> }
else { z = <some other expensive int expression>}

Note the preceding if/else must be entered on one source line.


Go does not support assignment expressions, only assignment statements.

Assert Statement
Go has no assert statement. Generally, Go has panics which can be used to achieve
a similar function, but they cannot be disabled at compile time like asserts can be.
Because of this, such use of panics is discouraged.

While and Do Statements


The Java while statement is replaced by the Go for statement (i.e., for acts like while).
There is no direct equivalent of the Java do statement, but the for statement can be used
to replace it.
Note that the Java for statement can be used as a while statement too.
For example:

var x = 0; for(; x < 10;) { ... ; x++; }

16
Exploring the Variety of Random
Documents with Different Content
stopping every carriage that they met, and compelling even ladies to
turn again and accompany them.
Meanwhile, Lafayette and Bailly, summoned by this strange news,
had hurried to the Hôtel de Ville, where they found the National
Guard and the French Guard drawn up, and demanding to be led to
Versailles. The French Guard declared that the nation had been
insulted by the Flanders regiment—the national cockade trampled
on; and that they would go and bring the king to Paris, and then all
should be well. Bailly and Lafayette attempted to reason with them;
but they, and thousands upon thousands of armed rabble again
collected there, only cried, "Bread! bread! Lead us to Versailles!"
There was nothing for it but to comply; and at length Lafayette
declared that he would conduct them there. He mounted his white
horse, and this second army, about three o'clock in the afternoon,
marched in the track of the amazons who had already reached
Versailles.
"It was on foot," says Mounier, "in the mud, and under a violent
storm of rain. The Paris women intermixed with a certain number of
men, ragged and ferocious, and uttering frightful howlings. As we
approached the palace, we were taken for a desperate mob. Some
of the Gardes du Corps pricked their horses amongst us and
dispersed us. It was with difficulty that I made myself known, and
equally difficult it was to make our way into the palace. Instead of
six women, I was compelled to admit twelve. The king received
them graciously, but separated from their own raging and rioting
class, the women were overcome by the presence of the king, and
Louison Chabry, a handsome young girl of seventeen, could say
nothing but the word 'Bread!' She would have fallen on the floor, but
the king caught her in his arms, embraced and encouraged her; and
this settled completely the rest of the women, who knelt and kissed
his hand. Louis assured them that he was very sorry for them, and
would do all in his power to have Paris well supplied with bread.
They then went out blessing him and all his family, and declared to
those outside that never was there so good a king. At this the
furious mob exclaimed that they had been tampered with by the
aristocrats, and were for tearing them to pieces; and, seizing
Louison, they were proceeding to hang her on a lamp-post, when
some of the Gardes du Corps, commanded by the Count de Guiche,
"interfered and rescued her." One Brunout, an artisan of Paris, and a
hero of the Bastille, having advanced so as to be separated from the
women, some of the Guard struck him with the flat of their swords.
There was an instant cry that the Guard were massacring the
people; and the National Guard of Versailles being called on to
protect them, one of them discharged a musket, and broke the arm
of M. de Savonières, one of the Life Guard. The firing on the Life
Guard by the National Guard then continued, and the Life Guard
filed off, firing as they went. The mob, now triumphant, attempted
to fire two pieces of cannon, which they turned upon the palace; but
the powder was wet and would not explode. The king, having
meanwhile heard the firing, sent the Duke of Luxembourg to order
that the Guard should not fire, but retire to the back of the palace.
The mob then retired into Versailles in search of bread, which
Lecointre, a draper of the town, and commander of its National
Guard, promised to procure them from the municipality. But the
municipality had no bread to give, or took no pains to furnish it, and
the crowds, drenched with rain, sought shelter wherever they could
for the night. The women rushed again into the Hall of the
Assembly, and took possession of it without any ceremony. Soon
after midnight the roll of drums announced the arrival of Lafayette
and his army. An aide-de-camp soon after formally communicated
his arrival to the Assembly; that they had been delayed by the state
of the roads; and that Lafayette had also stopped them to
administer to them an oath of fidelity to the nation, the law, and the
king; that all was orderly, and that they had nothing to fear.
Lafayette soon after confirmed this by leading a column of the
National Guard to the doors of the Assembly, and sending in this
message. The Assembly being satisfied, adjourned till eleven o'clock
the next day. Lafayette then proceeded to the palace, where he
assured the king and the royal family of the loyalty of the Guard, and
that every precaution should be taken for tranquillity during the
night. On this the king appeared to be at ease and retired to rest.
The mob attacked the palace in the night, but Lafayette prevented
an assault on the royal family, though two of the Guard were
butchered. The king during the night repeatedly sent to inform the
deputies of his intention to go to Paris.

THE BASTILLE.
[See larger version]
The Assembly had not paid him the respect to wait on him; but, at
the last moment, they passed a resolution that the Assembly was
inseparable from the person of the king, and appointed one hundred
deputies to attend him. Amongst them was Mirabeau. It was about
one o'clock when the king quitted Versailles amid a general
discharge of musketry, falsely, on this occasion, termed a feu-de-
joie. The king and queen, the dauphin, and the little daughter,
Monsieur, the king's brother, and Madame Elizabeth, the king's sister,
went all in one great State coach. Others of the royal household,
with the ladies of honour, and the one hundred deputies, followed in
about a hundred vehicles of one kind or other. The Mayor, Bailly,
received them at the barrier of Paris, and conducted them to the
Hôtel de Ville. So soon as they had passed the barrier, the numerous
procession were joined by the whole leviathan mob of Paris,
calculated at two hundred thousand men! It was night, and the
crushing and shouting throngs prevented the royal carriage from
more than merely moving all the way from the barrier to the Place
de Grève. At the Hôtel de Ville, Moreau de St. Mery addressed the
king in a long speech, congratulating him on his happy arrival
amongst his people—his "loving children of the capital." The poor
tired and dispirited king replied that he always came with confidence
amongst his people. Bailly repeated the words in a loud tone to the
people, but omitted the words "with confidence," whereupon the
queen said, with much spirit, "Sir, add 'with confidence';" so Bailly
replied, "Gentlemen, in hearing it from the lips of the queen you are
happier than if I had not made that mistake." The king was then
exhibited on the balcony to the mob, with a huge tricolour cockade
in his hat, at which sight, in French fashion, the people hugged and
kissed each other and danced for joy. It was eleven o'clock at night
before the miserable royal captives were conducted by Lafayette to
their appointed prison—for such it was, in fact—the great palace of
their ancestors, the Tuileries, which had been uninhabited for a
century, and had not been prepared for their reception. The
Assembly followed, and proceeded to work under the eyes of the
Paris commune and the people. Power was fast slipping from their
hands.
In such circumstances closed the year 1789. The intense excitement
which the rapid course of these French events had produced in
England had nearly superseded all other topics of interest. At first
there was an almost universal jubilation over this wonderful
revolution. The dreadful state of misery and oppression to which
France had been reduced; the fearful exactions; the system of
popular ignorance maintained by priestcraft; the abominable feudal
insolence; the abuse of lettres de cachet; and the internal
obstructions of customs and barriers between one province and
another, made every friend of freedom desirous of seeing all these
swept away. The early progress of their destruction was hailed with
enthusiasm in England. Even the retired and timid poet, Cowper
sang a triumphal note on the fall of the Bastille; but soon the bloody
fury of the populace, and the domineering character of the
Assembly, which did not deign to stop at the proper constitutional
limits, began to create distrust and alarm. Amongst the first to
perceive and to denounce this work of anarchy rather than of
reform, was Burke. In common with Fox and Pitt, and many other
statesmen, he had rejoiced in the fall of the corrupt government of
France; but he soon began to perceive that the people were
displaying the same ferocious character as in all their former
outbreaks. "If," he wrote to M. Menonville, a moderate Member of
the Assembly, "any of these horrid deeds were the acts of the rulers,
what are we to think of the armed people under such rulers? But if
there be no rulers in reality, and the chiefs are driven before the
people rather than lead them; and if the armed corps are composed
of men who have no fixed principle of obedience, and are moved
only by the prevalence of some general inclination, who can repute
himself safe amongst a people so furious and so senseless?" As he
continued to gaze, he was compelled to confess that he saw no
great and wise principles of legislation displayed by the Assembly;
but that it went on destroying, without knowing how to rebuild in a
manner likely to last or to work any one any good. The whole of the
constitution-making, which annihilated the royal power, which
erected no second chamber, but absorbed all authority into the
Assembly, a mixed and heterogeneous body, he declared to be a
bungling and monstrous performance. On the other hand, Dr. Price,
Dr. Priestley, and numbers of equally enthusiastic men, saw nothing
but what was animating in the progress of the French Revolution.
"The Revolution Society," including many of the highest names of
the Whig aristocracy, which was accustomed to meet on the 5th of
November, to celebrate the anniversary of the landing of William III.,
and the English Revolution of 1688, this year presented a glowing
address of congratulation to the French National Assembly, which
was carried over by Lord Stanhope and Dr. Price. Of course, they
and the address were received with great acclamation by the
Assembly. The admiration of the French Revolution spread over
Britain. Clubs were established, both in London and in the country, in
sympathy with it, and the press became very Gallican and
Republican in its tone, and there was much corresponding with
admirers of the revolution in France, especially with Thomas Paine,
who had now transferred himself from America, with a political
fanatic destined to acquire considerable attention, calling himself
Anacharsis Clootz, the "orator of mankind," and with many others.
We must open the year 1790 by reverting to the affairs of Britain,
and of other countries having an influence on British interests. The
Parliament met on the 21st of January; and, in the course of the
debate on the Address in the Commons, Fox took the opportunity to
laud the French Revolution, and especially the soldiers for destroying
the Government which had raised them, and which they had sworn
to obey. Burke, in reply, whilst paying the highest compliments to
the genius of Fox, and expressing the value which he placed on his
friendship, endeavoured to guard the House and country against the
pernicious consequences of such an admiration as had been
expressed by Fox. He declared the conduct of the troops disgraceful;
for instead of betraying the Government, they ought to have
defended it so far as to allow of its yielding the necessary reforms.
But the so-called reforms in France, he said, were a disgrace to the
nation. They had, instead of limiting each branch of the Government
for the general good and for rational liberty, destroyed all the
balances and counterpoises which gave the State steadiness and
security. They had pulled down all things into an incongruous and ill-
digested mass; they had concocted a digest of anarchy called the
Rights of Man, which would disgrace a schoolboy; and had laid the
axe to the root of all property by confiscating that of the Church. To
compare that revolution with our glorious one of 1688, he said, was
next to blasphemy. They were diametrically opposed. Ours preserved
the Constitution and got rid of an arbitrary monarch; theirs
destroyed the Constitution and kept a monarch who was willing to
concede reforms, but who was left helpless. Fox replied that he had
been mistaken by his most venerated and estimable friend; that he
was no friend to anarchy and lamented the cruelties that had been
practised in France, but he considered them the natural result of the
long and terrible despotism which had produced the convulsion, and
that he had the firmest hopes that the French would yet complete
their Constitution with wisdom and moderation. Here the matter
might have ended, but Sheridan rose and uttered a grand but ill-
considered eulogium on the French Revolution, and charged Burke
with being an advocate of despotism. Burke highly resented this; he
made a severe reply to Sheridan; and instead of the benefits which
he prognosticated, Burke, with a deeper sagacity, declared that the
issue of that revolution would be not only civil war but many other
wars.
The Whig party were in consternation at this sudden disruption of
the union of the heads of their party. A meeting was held on the
night of the 11th of February at Burlington House, which did not
separate till three in the morning. The result did not appear to have
been very satisfactory, and the fears of the Whigs were greatly
augmented by finding Pitt, who had hitherto praised the Revolution,
now express the great obligations of the country to Mr. Burke, for
the able warning which he had given against revolutionary
principles. The king made no secret of his abhorrence of these
principles. He considered the French Revolution as the direct result
of the American one; and having come to the conclusion that he had
himself erred by too much concession, he now censured the
concessions of Louis XVI. as fraught with certain calamity. All this
boded a decided resistance to the spirit of reform at home. There
was a new schism amongst the organs of the press. Many of the
newspapers still fostered in their columns the wildest hopes of
universal advantage to the cause of liberty from the French
Revolution; but others adopted the opinions and views of Burke—
and no few of the Whig and Foxite papers were of this class. The
effect of the alarm at the wild conduct of the French was speedily
seen in the refusal to consider the repeal of the Test and Corporation
Act, which was brought forward by Fox, on behalf of the Dissenters,
and a motion for parliamentary reform, introduced by Mr. Flood.
Both were strongly opposed, on the ground that this was not the
time to make any changes whilst so riotous a spirit of change was
near us, and was so warmly admired by many of our own people.
Both motions were rejected by large majorities.
On the 31st of March Dundas introduced the Indian Budget, and
soon afterwards Pitt congratulated the country on the fact that, so
far from the American war having injured the trade or the power of
Britain, the fact was that our shipping had increased considerably
more than one-third since 1773, and we had been continually
gaining strength even during the American war, and had relieved
ourselves of a load of expense always incurred by the government of
the States. This was an admirable argument for declaring all our
colonies independent, if it meant anything; but Pitt went on
seconding, and even surpassing Dundas in the prognostications of a
long peace. What such ministerial speeches were worth was shown
on the 5th of May, only a month and five days since the prophecy of
Dundas, and not three weeks since his own prophecy, by Pitt
announcing that the peace was already disturbed with Spain. It
appeared that the high prices obtained by the crews of Captain
Cook's ships, the Discovery and Resolution, at Canton, on his
exploring voyages in the South Seas, for the ill-selected, half-worn
furs brought from the north-west coast of America, had attracted the
attention of adventurers under the direct protection of the East India
Company. Mr. Mears, who had been a lieutenant in the royal navy,
and a Mr. Tippin, were sent out in command each of a vessel. Tippin
was wrecked on the coast of Kamtschatka; but Mears reached Prince
William's Sound and wintered there, opening a good trade with the
natives. In the spring of 1788 he discovered Nootka Sound, a fine
bay on the west side of a small island on the west coast of
Vancouver's Island. There he formed a settlement, making a bargain
with the chief for it. He went to Canton with furs and was opening a
fine trade, when the Spaniards came down on the settlement, seized
four British vessels, but permitted two United States' vessels to
remain unmolested. Part of the English crew were shipped in one of
the American vessels to China, and the rest suffered to depart in one
of their own ships after it had been plundered. The Spanish
commander then settled himself in the new colony, and Spain set up
a general claim to all coasts and islands, and the whole Pacific as far
as China.
Pitt, on the day mentioned, announced these facts, and declared
that his Majesty had demanded satisfaction from the Court of Spain
for the insult to our flag and for the usurpation of our settlement;
but that considerable armaments were making in the ports of Spain.
He called upon the House to address his Majesty, imploring him to
take all necessary measures for the vindication of our honour and
our rights. Fox naturally expressed his surprise at this
announcement, after the high assurances of such profound
prospects of peace little more than a fortnight before. He moreover
asserted that not only were the Ministers fully aware of all these
circumstances at the very moment when the Premier made these
statements, but that he had himself been aware of them a
considerable time before that. Pitt endeavoured to explain that all
the circumstances were not known when he professed such
confidence in peace; but these assertions were clearly as little true
as the former, for the British Government had received information
from the Spanish Government itself, as early as the 10th of the
previous February. Notwithstanding, the House supported the
Government warmly in its determination to resist the enormous
claims of Spain and to compel her to make satisfaction. Lord Howe
was desired to have a fleet in readiness, and the Spanish Court
having taken a high tone to Mr. Merry, our Minister at Madrid, Mr.
Fitzherbert was dispatched thither as our plenipotentiary. He arrived
at Madrid in the beginning of June. At first the Spanish Court were
very high, and applied to France for co-operation, according to
treaty; but France, in the throes of the Revolution, had no money to
spend in such armaments and, on second thoughts, Spain dreaded
introducing French revolutionary sailors amongst their own. They
soon, therefore, lowered their tone, agreed to surrender Nootka
Sound, make full compensation for all damages, and consented that
British subjects should continue their fisheries in the South Seas, and
make settlements on any coasts not already occupied. Captain
Vancouver, who had been with Cook as a midshipman in his last two
voyages, being present at his tragical death, was sent out in the
following year to see that the settlement of Nootka Sound was duly
surrendered to England. He saw this done, the Spanish commander,
Quadra, behaving in a very friendly manner; and he proceeded then,
during the years 1792 and 1793, to make many accurate surveys of
the western coasts of North and South America, in which the
Spaniards gave him every assistance. The British took formal
possession not only of Nootka Sound, but of the fine island called
after Vancouver. Pitt was highly complimented for his firmness and
ability in the management of this business.
Wilberforce, on the 27th of January, had obtained a committee of
inquiry into the slave trade. He, Clarkson, and the anti-slavery
committees, both in London and the provinces, were labouring with
indefatigable industry in collecting and diffusing information on this
subject. The Committee of the Commons found strong opposition
even in the House, and, on the 23rd of April, Lord Penrhyn moved
that no further evidence should be heard by the Committee; but this
was overruled, and the hearing of evidence continued through the
Session, though no further debate took place on the question.
In Ireland, the influence of the free notions of France was already
become broadly manifest, and though it resulted in no
unconstitutional act, it wonderfully invigorated the resentment of the
Irish against corruptions of Government. These truly demanded
reprehension and reform; but the Government of Pitt was strong,
and set both Ireland and reform at defiance. The Marquis of
Buckingham, the Lord-Lieutenant, was recalled, because he had not
been able to repress the movement in the Irish Parliament on the
Regency question. The Earl of Westmoreland was sent in his place;
but the Parliament still showed its resentment as strongly as ever,
and proceeded to delve vigorously into the sink of Government
corruption, and demand numerous corrections of abuses. Direct
motions on the subject were made in both Houses; in the Peers by
Lord Portarlington, in the Commons by Grattan, and, in truth, the
ministerial abuses of the Irish Government were disgraceful. Grattan,
on the 1st of February, pointed out the increased number of
commissioners of revenue, and moved that his Majesty be addressed
to inquire by whose advice this had been done. Next the increase of
the Pension List came under discussion; then the granting of no less
than fourteen Government offices to members of the Irish
Commons. Lastly was noticed the paltry withdrawal of Lord
Strangford's pension of four hundred pounds, which had been
granted him at the request of the Irish House of Lords, in
consequence of his small income, because he had voted against
Ministers on the Regency Bill, at the same time that numbers of men
who were not Irishmen, and had never done anything for Ireland or
any other country, were saddled on the Irish revenue in a variety of
sinecure posts and pensions. All these motions, however, were
rejected by large Ministerial majorities.
CAPTAIN COOK.
(After the Portrait by Dance, in Greenwich Hospital.)
[See larger version]
Before returning to the progress of the French Revolution, we must
pass a hasty glance over the affairs of the Netherlands and the north
of Europe. On the accession of Leopold, the brother of Joseph, a
sweeping change was made in Austrian policy. Leopold had ruled his
dominions, as Grand Duke of Tuscany, with remarkable wisdom and
benevolence. He had introduced many admirable reforms, and had
abolished the punishment of death—a grand example to the other
nations of Europe, and proved to be as sound as it was striking by
its results. He now made haste to assure the Netherlanders that all
their grievances should be redressed, and their old charters and
constitution restored. There had always been a considerable party in
favour of the Imperial Government, and this party was now greatly
increased by these wise assurances, which were relied on from the
known magnanimous character of the Emperor. A Congress met at
Reichenbach to endeavour to make a peace between Austria and the
Sultan, and this was accomplished by the mediation of Britain,
Prussia, and Holland, backed up by the threat of an immediate
invasion by Prussia, which was instigated by Pitt. The Ministers of
the three Powers that had brought about this peace of Reichenbach,
next guaranteed to Leopold all the possessions of Austria in the
Netherlands, on condition that he should restore all the ancient
privileges and constitution. On the other hand, the democratic party
had a congress of the United Belgic States, and this congress,
infected by the French Republican principles, declared still for
independence, in which they were at first encouraged by the
democrats in France. Lafayette reverted to the idea of a republic in
the Netherlands, which should form a barrier between Austria and
France, in case that Austria should attempt to invade France and
crush the Revolution, as appeared probable. Dumouriez was sent to
Brussels to inquire into the real state of the Netherlands, as the
Belgians had sent deputies to Paris to make certain overtures. The
result of Dumouriez's inquiries was so extremely unfavourable that
the French Government gave up all idea of meddling in Netherland
affairs. To Dumouriez, Van der Noot, the leader of the revolutionary
party, appeared a regular adventurer and impostor, the people to be
ignorant and bigoted; and the army, though full of courage, yet
destitute of good officers, money, clothing, and discipline.
Dumouriez, therefore, shrewdly concluded that France had better
make no present engagements with the Belgian reformers, but leave
the destinies of the country to be decided by the Congress at
Reichenbach, where the British, Dutch, and Prussian Ministers had
guaranteed the restoration of the government to Leopold, on the
renewal of the ancient institutions. Here again Pitt's foreign policy
was completely successful. Leopold easily crushed the rebellion, and,
having crushed it, proceeded to carry out the conditions of the
Convention of Reichenbach.
The Pitt Ministry figured with less success as regarded the
encroachments of Russia on the Turkish empire. The undisguised
policy of Catherine was to press on her operations against Turkey till
she had planted herself in Constantinople. Pitt continued as inactive
as if there were no danger at all, and the same policy actuated
Holland and Prussia. The least support given by these Powers to
Gustavus of Sweden would have effectually checked the Russian
designs in the East, and have raised Sweden into a position capable
of acting as a dead weight on Russian aggression. By very little aid
Gustavus would have been able to recover all the territories on the
eastern side of the Baltic which had been wrested from Sweden by
Russia, and would thus have kept a formidable power always, as it
were, at the very gates of St. Petersburg. But Gustavus was left,
with his brave heart but limited forces, to contend with Russia alone.
He kept down his disaffected nobles by cultivating the interests of
the people at large, and maintained a determined struggle with
Russia. He sent over the Prince of Anhalt with a small army of about
three thousand men at so early a season that the ground was
covered with ice and snow. The prince pushed on boldly towards St.
Petersburg, and made himself master of the strong forts and
defences at Karnomkoski, on the Lake Saima, within two days'
march of that capital. In April they were encountered by ten
thousand Russians under the command of General Ingelstrom,
whom they defeated after a desperate battle, leaving two thousand
Russians dead on the field. But the Prince of Anhalt was killed, and
the Swedes were not able, with a handful of men, to advance on St.
Petersburg, which was in fearful panic. Gustavus was more
successful at sea. He and his brother, the Duke of Sudermania,
fought the Russians with a very inferior force of ships off Revel, and
afterwards off Svenskasund. A considerable number of English
officers were serving in the Swedish fleet, amongst them one
destined to rise to high distinction, Sidney, afterwards Sir Sidney,
Smith. After two days' sanguinary fight at the latter place, Gustavus
beat the Russian Admiral Chitschakoff so completely that he took
four thousand prisoners, destroyed several of the largest Russian
ships, and took or sank forty-five galleys. Catherine was now glad to
make peace, which was concluded at Warela, near the river Kymen,
but with very different results to what would have been obtained
had Gustavus found that support which it was the obvious interest of
the whole civilised world to afford him. He agreed that each Power
should retain what it possessed before the war, thus conferring on
Russia the provinces torn from Sweden. Gustavus complained
bitterly of his treatment, and with ample cause.
During this campaign Catherine had made great progress in her road
to Constantinople. Suvaroff had reduced Ismail, a remarkably strong
place, which was the key of the lower Danube and the only
obstruction of any importance to the Russian advance to the Balkan
mountains and to Constantinople. This city had been taken by storm,
after a most desperate defence, on the 25th of December, and
when, with a little more resistance, the Russians would have been
compelled to quit the field by the severity of the season. The
carnage on this occasion was of the most frightful kind. The
Russians themselves lost nearly ten thousand men, and the Turks
thirty thousand people—men, women, and children, who were
indiscriminately butchered by the orders of Suvaroff, who said to his
soldiers, "Brothers, no quarter to-day, for bread is scarce." Every
horror possible in war, especially between barbarians, was
perpetrated by the Russian hordes in Ismail, who were guilty of the
most diabolical atrocities, such as burning whole streets, mosques,
and serais. Suvaroff sat down and wrote in Russian rhyme the words
quoted by Lord Byron in "Don Juan," "Glory to God and the Empress,
Ismail is ours." When Sir Charles Whitworth, the British ambassador,
next saw Catherine, she said, in allusion to some strong
remonstrances from Britain and Prussia, which took care not to go
beyond remonstrances, which were cheap—"Since the king, your
master, wishes to drive me out of Petersburg I hope he will permit
me to retire to Constantinople." The Czarina Catherine still continued
her war on the Ottoman empire. The Turks gained several
advantages over the Russians on the shores of the Black Sea, and
near the Danube, but they were severely repulsed in an attempt to
drive the Russians from their conquests between the Black and
Caspian Seas, and suffered a terrible slaughter on the banks of the
River Kuban. Then Britain, Prussia, Holland, and Austria, from the
Congress of Reichenbach, announced to Catherine that they were
resolved not to permit further encroachments on Turkey, but
Catherine paid not the slightest attention to their remonstrances.
A fresh war had broken out with us in India. Tippoo Sahib had
resumed hostilities. He conceived the idea of obtaining the aid of an
army from France, and of thus driving us, according to his vow,
entirely out of India. He opened communications with M. du Fresne,
the Governor of Pondicherry, which Britain had very imprudently
restored to France at the peace after the American war. M. Leger,
civil administrator in England, brought Tippoo's proposals to Paris.
Louis replied to the proposal that the matter too keenly reminded
him of the endeavour to destroy the power of Britain in America, in
which advantage had been taken of his youth, and which he should
never cease to regret. He had learned too deeply the severe
retribution which the propagation of Republicanism had brought
upon him. But, without waiting the arrival of the hoped-for French
troops, Tippoo had broken into the territories of the British ally, the
Rajah of Travancore, and by the end of 1789 had nearly overrun
them. Lieutenant-Colonel Floyd, suddenly attacked by Tippoo with
an overwhelming force, had been compelled to retire before him,
with severe losses amongst his sepoys. But General Medows
advanced from Trichinopoly with fifteen thousand men, and following
nearly the route so splendidly opened up by Colonel Fullarton, took
several fortresses. Tippoo retreated to his capital, Seringapatam; but
there he again threatened Madras; and General Medows was
compelled to make a hasty countermarch to prevent that
catastrophe. In the meantime, General Abercrombie landed at
Tellicherry with seven thousand five hundred men from the
presidency of Bombay; took from the Mysoreans all the places which
they had gained on the Malabar coast; restored the Hindoo Rajahs,
who, in turn, helped him to expel the forces of Tippoo from the
territories of the Rajah of Travancore, who was completely re-
established. This was the result of the war up to the end of the year
1790; but Tippoo still menaced fresh aggressions.
The new British Parliament met on November 26, and Ministers were
seen to have a powerful majority. The king announced, in his speech
from the throne, that hostilities had broken out in India with Tippoo,
and that a peace had been effected between Russia and Sweden,
and he mentioned the endeavours that were in progress for
restoring amity between the Emperor of Austria and his subjects in
the Netherlands. In the debate on the Address in the Commons, Fox
appeared inclined still to laud France, and to condemn our
interference in the Netherlands. His eyes were not yet opened to the
real danger from France, whose example was indeed exciting
popular disturbances in the Netherlands and in Poland. Already the
doctrines of Liberty and Equality had reached the ears of the
negroes in St. Domingo, who had risen to claim the rights of man so
amiably proclaimed by France, and the troops of France were on
their way thither to endeavour to put them down, in direct
contradiction of their own boasted political philosophy. In the Lords,
Earl Grey—the father of the Whig statesman—on the 13th of
December, called for the production of papers relating to Nootka
Sound. The motion was negatived by two hundred and fifty-eight
against one hundred and thirty-four votes. But the Marquis of
Lansdowne contended that Spain had a right to the whole of the
North American coast on which Nootka Sound is situated, and had
had it since the reign of Queen Elizabeth. He asserted that we had
insulted the weakness of Spain; and that Mr. Mears and the other
projectors of the trading settlement of Nootka Sound were a set of
young men of letters, seeking for novelties. He completely
overlooked the provocations which Spain had lately given us, and
her endeavours to enter into a conjunction with France against us.
He condemned Ministers for having alienated France, Spain, Russia,
Denmark, and Sweden, overlooking the fact that they had made
alliances with Prussia, Austria, Holland, and the Netherlands. Pitt's
cousin, Lord Grenville, replied to this one-sided view of things, and
proudly contrasted the position of Britain at this moment to what it
was at the conclusion of the American War, when Lord Lansdowne
himself, as Lord Shelburne, had been in the Ministry. Pitt, on the
15th of December, stated that the expenses of the late armament,
and the sums necessary to keep up the increased number of soldiers
and sailors for another year, before which they could not be well
disbanded, owing to certain aspects of things abroad, would amount
to something more than three millions, which he proposed to raise
by increasing the taxes on sugar, on British and foreign spirits, malt,
and game licences, as well as raising the assessed taxes, except the
commutation and land taxes. He stated that there was a standing
balance of six hundred thousand pounds to the credit of the
Government in the Bank of England, which he proposed to
appropriate to the discharge of part of the amount. He, moreover,
introduced a variety of regulations to check the frauds practised in
the taxes upon receipts and bills of exchange, which he calculated at
three hundred thousand pounds per annum. With this, Parliament
adjourned for the Christmas recess, and thus closed the eventful
year of 1790.
The Parliamentary Session of 1791 was opened, after the Christmas
recess, by Sir Philip Francis denouncing the war against Tippoo
Sahib in India, and eulogising that prince. He moved thirteen
resolutions condemnatory of the war; but they were all rejected, and
Dundas, as head of the Board of Control, moved three counter-
resolutions declaring that Tippoo had voluntarily broken the treaty
made with him in 1784, and that faith must be kept with the Rajah
of Travancore, whom he had attacked, as well as with the Nizam and
the Mahrattas, and these resolutions were carried without a division.
The British Ministry was at length becoming aware of the mischief of
allowing the Empress of Russia to make continual inroads on the
Turkish Empire. The British Ambassador, Mr. Fawkener, had been
instructed to inform Catherine that Britain could not quietly
acquiesce in these usurpations, which were seriously disturbing the
balance of power in Europe. Catherine replied, haughtily, that she
did not recognise the right of Britain to interfere, and that she
should keep possession of Oczakoff, and all her conquests between
the Bug and the Dniester. On the 28th of March Pitt communicated
this answer to the House, in a message from his Majesty, and that
he had deemed it necessary to come to an understanding with his
allies, Prussia and Austria, on the subject, and to maintain the fleet
in its augmented condition. He moved, the next day, an address to
his Majesty, thanking him for his care in these respects. The Whigs,
almost to a man, condemned this policy. Coke of Norfolk, Lord
Wycombe, Mr. Lambton, afterwards Earl of Durham, and others,
stoutly opposed it. Fox treated the idea of Russia having become a
power formidable to the peace of Europe as ludicrous. Both he and
Burke contended that there was nothing in the aggressions of Russia
to occasion any alarm; that Turkey was a decaying nation, which it
was useless to attempt to support; and that to bolster it up was only
to maintain a barbarous people in domination over Christian
populations. Fox upbraided the Government with their folly and
inconsistency, if such were their fears of Russia, in having till
recently encouraged her in her plan of aggressions in that direction.
He reminded them that, twenty years ago, Great Britain, on war
breaking out between Russia and the Porte, had aided Catherine in
sending a fleet to the Mediterranean, and had thus enabled her to
acquire a maritime force in the Black Sea. The truth, however, was
that it was not the present Ministry that had committed this folly, but
a Whig Ministry, of which Fox was one. He confessed to this, and
also to the fact that in 1782, when Catherine seized more completely
on the Crimea and Kuban Tartary, France and Spain had urged us to
unite with them in preventing this, but that we had declined, and
these countries had become permanently united to Russia. Now all
this was, in truth, a simple confession of the incapacity of the Whigs,
and of Fox himself included, to see the dangerous tendency of the
Russian policy, and the only circumstance on which he could justly
condemn the Ministry of Pitt was for not strenuously supporting
Turkey and Sweden, the ally of Turkey against Russia, when they did
see this tendency. By mean and parsimonious conduct they had
allowed Sweden to be driven out of her territories on the eastern
shore of the Baltic by Russia, when, had they given her but
moderate support, that Power would have become a permanent
check on the aggressive spirit of Russia. The motion of Pitt was
carried by a large majority. A few days afterwards Mr. Grey renewed
the subject in a series of resolutions, condemning all interference on
behalf of Turkey, and contending that Russia was only weakening
instead of strengthening herself by extending her dominions. But
Pitt, in reply, showed the very obvious facts that the retention of
Oczakoff opened the way to Constantinople, and that the possession
of Constantinople prepared the way for the seizure of Egypt, and the
supremacy of the Mediterranean, with the most formidable
consequences to our commerce. The resolutions of Grey were
negatived; but twice again during the session the Whigs returned to
the charge—on the 15th of April and on the 25th of May,—but with
no better success. The armament was maintained, but the isolated
threats of England had little effect on Catherine. Pitt was accordingly
compelled to change his policy, and acquiesce in a peace by which
she retained the territory between the Bug and the Dniester, and the
fortress of Oczakoff.
SCENE IN THE HOUSE OF COMMONS: BREACH BETWEEN BURKE AND
FOX. (See p. 379.)
[See larger version]
On the opening of the Session, the king called the attention of
Parliament to the state of Canada. That colony had flourished since
it had come into the possession of Britain, especially since the
passing of the Bill of 1774, which had given freedom to the Roman
Catholic church there, the church of the French inhabitants. But one
part of the colony was still inhabited by the descendants of the
French, and another by those of the English and Americans. It was,
therefore, found desirable to put an end to the competition which
still existed, from differences of faith and of national sentiments and

You might also like