Go For Java Programmers Learn The Google Go Programming Language 1st Edition Barry Feigenbaum Phd instant download
Go For Java Programmers Learn The Google Go Programming Language 1st Edition Barry Feigenbaum Phd instant download
https://ebookbell.com/product/go-for-java-programmers-learn-the-
google-go-programming-language-1st-edition-barry-feigenbaum-
phd-35235816
https://ebookbell.com/product/go-for-java-programmers-learn-the-
google-go-programming-language-1st-edition-barry-feigenbaum-35192312
Beginning Bazel Building And Testing For Java Go And More 1st Edition
Pj Mcnerney
https://ebookbell.com/product/beginning-bazel-building-and-testing-
for-java-go-and-more-1st-edition-pj-mcnerney-53001846
https://ebookbell.com/product/grpc-up-running-building-cloud-native-
applications-with-go-and-java-for-docker-and-kubernetes-kasun-
indrasiri-danesh-kuruppu-22077240
Go For Devops Learn How To Use The Go Language To Automate Servers The
Cloud Kubernetes Github Packer And Terraform John Doak David Justice
https://ebookbell.com/product/go-for-devops-learn-how-to-use-the-go-
language-to-automate-servers-the-cloud-kubernetes-github-packer-and-
terraform-john-doak-david-justice-49119422
Go For The Company Carnival Of Mysteries Ander C Lark
https://ebookbell.com/product/go-for-the-company-carnival-of-
mysteries-ander-c-lark-51356722
https://ebookbell.com/product/go-for-no-yes-is-the-destination-no-is-
how-you-get-there-fenton-7185910
https://ebookbell.com/product/go-for-the-gold-atalanta-1st-edition-
kate-mcmullan-58917338
https://ebookbell.com/product/go-for-gold-inspiration-to-increase-
your-leadership-impact-john-c-maxwell-46390882
https://ebookbell.com/product/go-for-the-green-jeff-hopper-48930310
Go for Java
Programmers
Learn the Google Go Programming
Language
—
Barry Feigenbaum, Ph.D.
Go for Java Programmers
Learn the Google
Go Programming Language
Introduction������������������������������������������������������������������������������������������������������������xix
Assessments�������������������������������������������������������������������������������������������������������xxxv
v
Table of Contents
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
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
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.
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
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
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
• Easy to learn
• 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
• Quick compilation
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.
32%
30%
25%
24%
21%
20%
20%
18%
16%
15%
15% 14%
10%
5%
0%
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
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:
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:
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
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
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 description of the Go language and its key features with a look at using Go in
practice:
xxx
Introduction
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
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
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
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 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).
5
https://en.wikipedia.org/wiki/Von_Neumann_architecture
8
Chapter 1 A Brief Look at Go vs. Java
• Java has while, do, and for statements; Go combines them all into
just for.
6
https://en.wikipedia.org/wiki/Structured_programming#Elements
9
Chapter 1 A Brief Look at Go vs. Java
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).
11
Chapter 1 A Brief Look at Go vs. Java
12
Chapter 1 A Brief Look at Go vs. Java
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
8
https://dzone.com/articles/welcoming-the-new-era-of-java
14
CHAPTER 2
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;
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
var z = x > y ? x : y;
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>}
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.
16
Chapter 2 What Java Has That Go Does Not
is the same as
17
Chapter 2 What Java Has That Go Does Not
Go does not support Java Lambdas (function signatures compiled into class
instances). Instead, Go supports first-class functions (often literals) that may be passed as
parameters. Go does not support Method References (simple names for lambdas passed
as parameters).
Go supports interfaces in a different way than Java. Go’s interfaces allow Duck Typing.
Go’s interfaces do not require that they be implemented explicitly (no implements clause
is needed in Go); any type that has methods that match all the methods of the interface
implicitly implements the interface. In general, Go’s approach is more flexible.
Java 8 and beyond allows implemented (concrete) methods in interfaces. Go does
not. Java allows constants to be declared in interfaces; Go does not. Java allows subtypes
to be declared in interfaces. Go does not.
Consider these tenants of OOP:
Java supports (but not necessarily enforces) all the preceding tenants. Go does not.
Go supports these tenants as follows:
18
Chapter 2 What Java Has That Go Does Not
6. Supported but often not used (struct fields are very often public).
7. Not supported.
1
https://en.wikipedia.org/wiki/Simula
2
https://en.wikipedia.org/wiki/Smalltalk; Smalltalk introduced the Graphical User
interface (GUI).
3
www.toptal.com/c/after-all-these-years-the-world-is-still-powered-by-c-programming
19
Chapter 2 What Java Has That Go Does Not
20
Chapter 2 What Java Has That Go Does Not
S
ource Annotations
Go has no Annotations. Go Struct fields can have tags, which serve a similar but much
more limited role.
Annotations, along with function streams and lambdas, make Java (at least partially)
a declarative language.4 Go is almost purely an imperative language.5 This is by choice.
This tends to make Go code both more obvious and more verbose.
Note Go has a similar concept to Java compile-time annotations where a source
file can include special comments (called build constraints) that the builder interprets
to change how code is processed. For example, the target operating system to generate
code for can be specified by a comment like this at the very start of a source file:
// +build linux,386
that will cause the file to only build for the Linux operating system (OS) and 386-based
architectures.
There is an alternate (and generally preferred) syntax; the previous comment can
also be written as
//go:build linux,386
Note some constraints, such as the target OS and/or hardware architecture, can be
embedded in the Go file names. For example
xxx_windows.go
4
https://en.wikipedia.org/wiki/Declarative_programming
5
https://en.wikipedia.org/wiki/Imperative_programming
21
Discovering Diverse Content Through
Random Scribd Documents
puissant auprès de ses femmes, même si tu le déclares menteur et
lâche, tu dois employer le mot noble.
—Tu m'enseigneras donc les mots nobles,» répondit l'étranger
avec douceur. Haamanihi réfléchit, le temps de pagayer trois ou
quatre fois; puis, sentant éveillé le bon vouloir de l'autre, il songeait
à lui glisser une habile requête, à propos de ce mousquet... Mais on
accostait le navire. Le chef étranger monta rapidement. La pirogue
Arc-en-ciel louvoyait avec méfiance à quelques longueurs. On lui fit
signe, elle vint ranger le flanc élevé: le grand Arii s'apprêtait à bondir
vers le ciel, quand un bruit étonnant l'étourdit. Il retomba sur le
balancier, stupéfait comme le manant frappé d'un coup de massue. Il
se tenait tout prêt à sauter à l'eau, à fuir. La personne sacrée
soufflait de peur.
Haamanihi le rassura, en criant que c'était là salut de bienvenue
des étrangers vers le grand Arii:—«Ils disent que dans leurs îles on
s'adresse de la sorte aux grands chefs, par la voix des gros
mousquets.
—Bien! Bien!» reprit Pomaré. La crainte envolée, il s'enorgueillit
d'être traité, par les arrivants, comme un maître en leur pays.
Néanmoins il observa qu'un salut de ce genre—un seul—lui serait
satisfaisant. Puis il monta pesamment à bord.
La troupe curieuse se répandait partout. On admira vivement que
les profondeurs du navire pussent contenir tant de choses et tant
d'hommes.—Mais, où donc se cachaient les femmes étrangères?
Elles n'apparurent que de loin, se distinguant aisément de leurs tané
par les vêtements d'abord, leurs chevelures et leur maigreur.
Immobile et grave, Pomaré considérait tous ces gens avec
indifférence. Le chef étranger lui offrit de descendre dans le creux du
bateau. L'Arii ne parut point y mettre de hâte. Il se refusait, sans
doute, à courber sa tête sous des planches assemblées... Mais son
épouse, par un autre passage, l'avait précédé. Il entendait ses rires
et ses paroles satisfaites, et se résolut à la rejoindre.
Pour fêter la présence de Pomaré, les étrangers répandaient avec
largesse cette boisson qui brûle et rend joyeux. Eux-mêmes
prétendaient s'abstenir. Peut-être en réservaient-ils l'usage à leurs
rites solennels et secrets. Haamanihi n'ignorait point les merveilleux
effets qu'on pouvait attendre de ce áva, plus rude et plus âcre que
tous les áva maori; et il supplia pour en obtenir encore:
—«J'ai besoin de courage!» affirmait-il, «de beaucoup de
courage: j'ai deux, hommes à tuer pour le sacrifice de cette nuit.»
Les étrangers frémirent en manifestant une stupide horreur. Mais
Pomaré, gaîment, s'était emparé du vase allongé contenant la
précieuse boisson:
—«Donnez-moi votre áva piritané... Nous sommes fétii,
maintenant!» On répondit:
—«Cette boisson-là n'est pas bonne pour les chefs; elle rend
malade; elle trouble la vue et la démarche...
—Pas bonne pour les chefs? Pas bonne pour les autres? Je la
boirai donc à moi tout seul, comme ceci.» Et Pomaré s'en emplit la
bouche. Ses yeux roulaient et larmoyaient. Il toussa beaucoup, et
soudain, frappa violemment de sa tête—semblable au faîte d'un
mont—les poutres du navire! Or, ses gens, le considérant avec
scandale, s'apprêtaient à calmer sa digne violence... le chef riait au
contraire! Puis il reprit une grande majesté, et gravit les degrés de
bois—taillés pour un enfant—qui menaient au toit du bateau. Alors il
désira danser un peu et commença le ori dans lequel on chante:
Aué! la femme est... mais Haamanihi l'arrêta:
—«Les Piliers de ton corps ne te porteraient pas! Tu as bu le áva
des étrangers. Prends garde! Et dirige bien, où tu marches, les
Eclairs de tes yeux! Eha! l'Arc-en-ciel!» Déjà le chef avait sauté au
hasard dans un pahi de manant, et il réclamait à voix forte:
—«Le salut! Le salut! comme aux Arii Piritané!»
Il attendit avec défiance et fierté que la voix du gros mousquet
tonnât de nouveau. Alors il s'étendit, comme ensommeillé, dans le
creux de la pirogue. Son épouse pleurait de dépit: elle voulait dormir
avec un prêtre étranger. Haamanihi, seul, qui n'avait pas bu selon la
soif de son gosier, implorait encore, en s'en allant, «la boisson qui
donne le courage...»
ORO
Le temps des pluies prenait fin. Oro, par sa présence au
firmament de l'île, avait fécondé la grande Hina-terrestre, et s'en
allait, imperturbable, avec son cortège de nues, vers d'autres terres,
ses autres femelles, pour les féconder aussi. Il convenait de pleurer
sa retraite; car le Resplendissant, jaloux d'hommages, aurait pu
s'attacher à des pays plus dévots, et tarder en son retour.—Ainsi
jadis, affirmaient les gens de Nuú-Hiva: le soleil-mâle n'avait point
reparu. Mais l'homme Mahui, plus fort que tous les hommes,
poursuivant l'atua vagabond jusque par les confins du monde, avait
saisi les cheveux de lumière, et fort heureusement ramené le soleil
dans le ciel Maori,—où il le fixa par des nœuds.
C'était aux Arioï, issus de Oro, que revenait le soin de ces
lamentations d'absence. Ils sanglotaient donc, pendant les nuits
prescrites, avec une grande dignité. Néanmoins, comme le
fécondateur, en s'éloignant, dispensait à ses fidèles de
surabondantes récoltes, on pouvait, sans l'irriter, mêler à la tristesse
rigoureuse cette joie des sens agréée par lui en guise des plus riches
offrandes: on pouvait s'éjouir sans scrupules. Et Térii prenait pitié de
ses frères dans les autres îles, qui, de ce double rite, se réservaient
les seules douleurs.
Il attendait ces fêtes avec hâte, se flattant d'y obtenir enfin, par
son impeccable diction, le rang quatrième entre les haèré-po—ce
rang que distingue le tatu de l'épaule: car il négligeait, maintenant,
comme inutiles à sa mémoire assurée, les faisceaux, les baguettes,
et les tresses que l'on accorde aux nouveaux récitants. Parfois,
malgré l'incantation, des craintes indécises le harcelaient, comme
des moustiques importuns. Voici qui l'irritait par dessus tout: le
maraè de Papara n'était point, cette saison-là, désigné pour
l'assemblée. Les prêtres d'Atahuru s'étant faussement prévalus d'une
majesté plus grande, Pomaré, dont ils étaient le meilleur appui,
n'avait pu les récuser. Mauvais présage, et nouveaux sortilèges! Térii
n'entrevit donc pas sans inquiétude le véa-des-fêtes, envoyé par
l'Arii vers le cercle de l'île, passer en proclamant aux chefs, aux
possesseurs de terres, aux manants, la célébration, sur la rive
Atahuru, des adieux solennels aux esprits.
Comme le jour tombait, l'on s'étira pour les danses. Alors des
prêtres de haut rang s'inquiétèrent; et ils haranguaient la foule: quoi
donc! on allait s'éjouir quand les atua, les chefs et la terre Atahuru
supportaient cette insulte et toutes ces profanations: l'oubli d'un
haèré-po, la ruée du peuple à toucher l'autel?—Mais le bon sommeil
avait passé: les dieux, n'avaient-ils point dormi de même, puisque
rien ne se manifestait dans les nuages ou sur les eaux... Et pour la
faute, on s'en prendrait au coupable,—quelques riverains, sans hâte,
se mirent à sa recherche,—ou bien à d'autres, ou bien à personne.
Les atua se taisaient toujours, l'Arii restait indifférent, et la fête, à
peine suspendue, reprit tous ses ébats: vite, on ménageait des
places rondes où préparer la boisson rassurante, le áva de paix et de
joie,—que les Nuú-Hiviens, dans leur rude langage, appellent kava.
Autour du bassin à quatre pieds creusé dans un large tronc de
tamanu, s'assemblaient par petits groupes les gras possesseurs-de-
terres, leurs fétii, leurs manants, leurs femmes. Une fille, au milieu
du cercle, écorçait à pleines dents la racine au jus vénérable, puis,
sans y mêler de salive, la mâchait longuement. Sur la pulpe broyée,
crachée du bout des lèvres avec délicatesse dans la concavité du
tronc, elle versait un peu d'eau. On brassait avec un faisceau de
fibres souples qui se gonflaient de liquide, et que la fille étreignait
au-dessus des coupes de bois luisantes. A l'entour, les tané buvaient
alors la trouble boisson brune, amère et fade, qui brise les membres,
mais excite aux nobles discours.
Les cercles s'agrandirent. Des torches de bambous desséchés
craquaient avec des éclats rouges. Déjà les gens du rivage Taütira,
parés de couronnes, la figure peinte, le corps enroulé de fines
étoffes longuement battues, lançaient des cris et s'agitaient. Durant
vingt nuits ils avaient redit avec soin chaque part de leur chant. Les
femmes, au milieu des groupes, jetaient un appel prolongé, perdu,
qui retombait sur les mugissements des hommes. Ceux-ci
entrechoquaient d'un battement égal de petits cailloux cliquetants,
et ils cadençaient leurs soubresauts. Les voix montaient avec charme
sur des contours habilement apprêtés, et les paroles, enjolivées de
beaux sons étendus, s'improvisaient, comme il convient, au hasard
des lèvres.
Or, les Nuú-Hiviens scrupuleux redoutaient à mélanger leurs
chants aux ébats du peuple en liesse. La joie pérennelle de la terre
Tahiti leur pesait; surtout lorsque le kava, aiguisant les esprits,
réveillait en eux le respect des atua et du culte. Alors ils se
rémémoraient les Dires impérissables, et si réservés que l'homme
mort Pukéhé avait dû reparaître tout exprès pour les enseigner aux
autres hommes. Alors tressaillaient leurs appétits guerriers. Ils
attendaient, au retour dans leurs îles, ces festins héroïques où il
importe de mâcher le cœur de l'ennemi le plus audacieux. On les vit
se retirer dans la montagne. Et bientôt, de leur repaire, descendit un
murmure qui s'enflait, se perdait, puis se gonflait de petites
clameurs, enrouées d'abord, débonnaires, satisfaites et menaçantes
enfin: les Nuú-Hiviens entonnaient ce péhé où s'expriment, après un
signal, la faim, la chasse, le rut et la mort du cochon propitiatoire.
LE PRODIGE
Térii fuyait sur le récif. Il avait à grand'peine échappé à la foule
hargneuse. Hagard et haletant, il détalait sans trêve. Des balafres
brûlantes, poudrées de safran, coupaient son visage. Ses couronnes
flétries glissaient de la tête aux épaules. Son maro déchiré dénudait
ses cuisses, et, trempé d'eau de mer, collait aux genoux qui s'en
embarrassaient. Une vague s'épaula, frémit, et lui vint crever sur la
tête: il roula, piqué par les mille pointes de corail vivant qui
craquaient dans sa peau. Se redressant, et sautant pour esquiver
une autre vague, il s'effrayait: c'était là jadis un châtiment de prêtre
impie!... Des haèré-po, même des sacrificateurs, avaient dû, pour
des fautes moindres, courir tout le cercle de l'île. On les voyait,
assaillis par la houle, franchir en nageant les coupures du récif,
reprendre pied et s'élancer encore, harcelés de gens en pirogues qui
brandissaient des lances. Térii sentit que sa fuite douloureuse était
une première vengeance des dieux rancuniers;—mais il trouva bon
qu'elle offrit, à la fois, un moyen d'échapper aux poursuites: nul ne
se risquait, derrière lui, dans la mer obscure.
Le récif, après un grand détour, revenait côtoyer les terres. Le
fugitif interrogea la nuit: tous les chants étaient morts,—mangés par
le vent, peut-être? Des lueurs éparses vacillaient seules par instant.
Alors, il souffla. Puis, incertain, lourd de dépit et défiant l'ombre, il
vint rôder aux abords de la fête, parmi les couples endormis.
Le firmament nocturne blêmissait. Dans l'imprécise clarté
nouvelle, Térii heurta des corps étendus. Pas un ne s'éveilla: il
reconnut les guerriers Nuú-Hiviens et s'étonna de les voir appesantis
et veules: le áva maori ne donne point, aux vivants qui sommeillent,
ces faces de cadavres ni cet abêtissement... L'un d'eux, le front
ouvert, n'était plus qu'un mort en vérité. Un autre qui se vautrait à
son flanc, le tenait serré comme un fétii.—Rien à redouter de ceux-
là! Térii les enjamba. Il piétinait des monceaux de vivres à demi
dévorés, des cochons dépouillés, prêts pour la cuisson, des noix de
haàri éventrées, des colliers et des parures pour la danse.
Un clair rayon de jour éveillé dansa sur les cimes. Dans la
fraîcheur du matin, des femmes se dressèrent. Leurs yeux étaient
pesants; leurs gestes endoloris de fièvres amoureuses. Mêlées aux
hommes qui, cette nuit-là, les avaient enlacées, et nues sous les
fleurs souillées, elles étendaient les bras, s'écrasaient le nez et la
bouche de leurs paumes humides, et joyeuses dans l'air froid,
frissonnaient en courant à la rivière. Térii se souvint que sa dernière
épouse avait paru dans la fête: elle reposait près d'un façonneur-de-
pirogues. Il la secoua. Tous deux coururent s'ébrouer dans les eaux
de la grande Punaáru. Puis, vêtus d'étoffes abandonnées, ils
marchaient vers ce coin du ciel d'où souffle le maraàmu-sans-trêve,
pour regagner, comme on regagne un asile, la terre sacrée Papara.
«Or, Téaé, comme l'île avait faim, réunit les hommes de sa terre,
les hommes maigres et desséchés; les femmes aux mamelles taries;
et les enfants pleurant pour manger.
—E aha! Téaé.
Téaé leur dit:—Je vais monter dans la vallée. Je dirai vers Té Fatu
le maître, des parlers puissants. Allons ensemble dans la vallée.
—E rahi! Téaé.
Ils le suivirent. Les torrents avaient soif, et la grande Punaáru
descendait, goutte à goutte, dans son creux de cailloux secs.
Derrière eux venaient des cochons maigres, réservés pour la faim
des derniers jours.
—Ahé! Téaé.»
[3]Arbre-à-pain.
ebookbell.com