© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
B. Feigenbaum, Ph.D.Go for Java Programmershttps://doi.org/10.1007/978-1-4842-7199-5_5

5. Go Basic Features

Barry Feigenbaum, Ph.D.1  
(1)
Austin, TX, USA
 

In this chapter, we will drill down some of the important characteristics that make Go what it is. When we are done with this chapter, you should be able to characterize the finer Go language similarities and differences from Java.

Language Keywords

The Go reserved (cannot be used for any other purpose) words are
break, case, chan, const, continue, default, defer, else, fallthrough, for, func, go, goto, if, import, interface, map, package, range, return, select, struct, switch, type, var

Table 10 Go reserved words

Both Java and Go have keywords, some of which are reserved words. They are listed in Table 5-1. They are listed in the same row if they have the same/similar purpose. Some of the keywords are reserved words (can only be used as defined in the language and never as a variable name).
Table 5-1

Reserved Word and Keyword Comparison

Java

Go

Purpose

 

_

Discardable value; not in Java

abstract

 

Go has no equivalent

assert

 

Go has no direct equivalent; using panics is similar

boolean

bool

Same

break

break

Same

byte

byte

Unsigned in Go; signed in Java

case

case

Same; Go has some extensions

catch

 

Go has a built-in recover() function in a deferred function instead of try/catch

 

chan

Java has no equivalent

char

 

Go has a rune (32-bit) type instead

class

 

Go has no OOP; a struct type is the closest approximation

const

const

Unused in Java

continue

continue

Same

default

default

Same in switch; no similar visibility in Go. In Go, no use on functions

 

defer

Like Java try/finally

do

 

Go has no direct equivalent

double

 

Go has a float64 type

enum

 

Go uses int (iota) constants instead (like C)

else

else

Same

extends

 

Go has no inheritance

 

fallthrough

Creates Java switch fall through behavior

final

 

Go has a const declaration instead

finally

 

Go uses a deferred function instead of try/finally

float

 

Go has a float32 type

for

for

Similar

 

func

Java has Lambdas

 

go

Java has threads

goto

goto

Unused in Java; in Go, similar in purpose to break but can be used outside a loop

if

if

Same

implements

 

Go does this implicitly

import

import

Similar

int

int

Go also has an int32 type

instanceof

(type)x

x.(type)

Go has a type assertion test instead; casting part of assertion

interface

interface

Similar role

long

 

Go has an int64 type

 

map

Java has a HashMap (and others) library type

native

Function definition without a body

Go has no direct equivalent; but CGo does a similar thing

new

new

Creates an object; Go has a built-in new function that does similar; Go has no notion of constructors associated with a type

package

package

Similar role

private

 

Go uses a lowercase name (more package protected)

protected

 

Not needed; Go has no inheritance

public

 

Go uses an uppercase name

 

range

Java has a for statement

return

return

Same; Go can return multiple values

 

select

Java has no equivalent

short

 

Go has an int16 type

static

 

Go has global (vs. class) variables

strictfp

 

Go has no equivalent

 

struct

Java class can be used in a similar way

super

 

Go has no equivalent

switch

switch

Similar; Go has extensions

synchronized

 

Go has no direct equivalent; libraries can provide similar behavior

this

 

Go can use any name for this role

throw

 

Go has a built-in panic function instead

throws

 

Not needed; Go has no exceptions to declare

transient

 

No equivalent in Go

try

 

Go has no direct equivalent but supports a try/catch and try/finally like behavior

 

type

Java has no equivalent

var

var

Java uses a type name (except optionally for block locals)

void

 

Omitted return type serves the same purpose in Go

volatile

 

Go has no equivalent

while

 

Go has for

Operators and Punctuation

Both Java and Go have operators and punctuation. Many have the same or similar purpose, but each language has some unique ones. Some operators work a bit differently due to the signed vs. unsigned integer types Go supports (Java does not support unsigned integers in the language). Also, Go does not automatically convert smaller-sized numbers into larger-sized numbers (e.g., byte -> short -> int -> double); such conversion must be explicit in Go. Table 5-2 summarizes the Go and Java operators and how they compare to each other.
Table 5-2

Java and Go Operator Comparison

Java

Go

Purpose

+

+

Same; (binary) addition and (unary) positive or string concatenation

-

-

Same; (binary) subtraction and (unary) negative

*

*

Same (binary) multiplication; in Go, also pointer declaration and (unary) dereference

/

/

Same; division

%

%

Same; modulo

&

&

Same; bit-wise and; in Go, also (unary) take address of

|

|

Same; bit-wise or

^

^

Same; bit-wise exclusive-or; (unary) not on Booleans in Go

<<

<<

Same; bit-wise shift left

>>

>>

Same; bit-wise shift right

>>>

 

Unsigned bit-wise shift right; in Go, use >> with unsigned int types

 

&^

Bit clear (and not); not in Java

=

=

Assignment; in Go, a statement, not an operator

+=

+=

Plus assignment; in Go, a statement, not an operator

-=

-=

Minus assignment; in Go, a statement, not an operator

*=

*=

Multiply assignment; in Go, a statement, not an operator

/=

/=

Divide assignment; in Go, a statement, not an operator

%=

%=

Modulo assignment; in Go, a statement, not an operator

&=

&=

And assignment; in Go, a statement, not an operator

|=

|=

Or assignment; in Go, a statement, not an operator

^=

^=

Exclusive-or assignment; in Go, a statement, not an operator

<<=

<<=

Shift-left assignment; in Go, a statement, not an operator

>>=

>>=

Shift-right assignment; in Go, a statement, not an operator

>>>=

 

Unsigned shift-right assignment; not in Go

 

&^=

Bit clear assignment; not in Java

&&

&&

Same; logical and; short circuit

||

||

Same; logical or; short circuit

++

++

Auto-increment; in Go, only postfix; in Go, a statement, not an operator

--

--

Auto-decrement; in Go, only postfix; in Go, a statement, not an operator

==

==

Same; equals test

!=

!=

Same; not equals test

<

<

Same; less than test

<=

<=

Same; less or equals test

>

>

Same; greater than test

>=

>=

Same; greater or equals test

 

:=

Simple (aka short) declaration; not in Java

...

...

Similar; varargs declaration; in Go, list expansion on function arguments

(

(

Same; open parameter list or open sub-expression

)

)

Same; close parameter list or close sub-expression

[

[

Same; open index

]

]

Same; close index

{

{

Same; open block or initialization list

}

}

Same; close block or initialization list

;

;

Same; in Go, can often be omitted if placed at the end of the line

:

:

Same; separator

@

 

Annotation indicator; not in Go

::

 

Method reference; not in Go

.

.

Same; field reference

,

,

Same; list or argument separator; not an operator in Go

~

 

No bit-wise; not in Go

?:

 

Ternary choice; not in Go

!

!

Same; logical not

->

 

Lambda expression declaration; not in Go

 

<-

Send to or receive from (based on position) a channel; not in Java

instanceof

(type)value

x. (y)

Test type; not in Go; Go has an assertion expression that casts a type and returns a Boolean if the cast is possible; can if test the Boolean

new

New

make

Allocate and construct an object; Go has functions new and make instead. Also, Go structs can be declared and the address taken, which results in the same action. In Go, new does not run any constructor; that is the role of make

Both Java and Go have the relational operators (==, !=, <, <=, >, >=), but they do not always work the same. For example, to compare two strings s1 and s2 (or any other reference type) for equality in Java, one must use
if(s1.equals(s2)) { ... }
While in Go, one would use
if s1 == s2 { ... }

This comparison only works if the type is comparable. Most built-in types are. See the Go Language Specification for details. Slice, map, and function values are not comparable except to the nil value. Pointer, channel, and interface values can also be compared to nil.

The following has a different meaning in Java where the references are being compared (i.e., a sameness test):
if(s1 == s2) { ... }
This is a test to see if the s1 and s2 references are to the same object (i.e., are aliases of each other). To get the equivalent test in Go, a test like this is needed that compares the address (not values) of the strings:
if &s1 == &s2 { ... }
Java does not implicitly support relational tests of reference types; the type itself must provide some means to do that. For strings, the test could be
if(s1.compareTo(s2) < 0) { ... }
In Go, this would be
if s1 < s2 { ... }

This comparison only works if the type is ordered by some means. In Go, many types are. See the Go Language Specification for details. For example, strings are ordered as a byte array with shorter strings having implied additional zero cells.

Like in Java, the && and || operators are short circuit and may only evaluate the left argument.

The Go take address (&, aka address of) unary operator returns the address of its operand, which must be addressable (have a storage location; e.g., a constant and many expressions do not). Java has no equivalent to this action. For any value of type T, the & operator returns a value of type *T. One cannot take the address of a nil value.

Addressable values are
  • A declared variable

  • A pointer dereference (*p) – Returns p

  • An array or slice index expression

  • A struct field selector expression

  • A composite (array, slice, map, struct) literal

Note for any expression exp that causes a panic, the expression &exp will also.

Go Operator Precedence

Java operator precedence is complex and will not be restated here (see the Java Language Specification for more details). Go precedence is generally simpler. Unary operators have precedence over binary operators.

Unary from high to low:
  • Wrapping ( ... )

  • Prefix + - * &

  • Suffix [ ... ] ( ... )

Note in Go ++ and -- are statements, not operators.

Binary from high to low:
  • / % << >> & &^

  • + - | ^

  • == != < <= > >=

  • &&

  • ||

It is best practice that when in doubt use parentheses ( ... ) to clarify precedence, especially for unary operators.

Note Go has the bit clear (&^) operator that Java does not.

The expression x &^ y is effectively x AND (NOT y).

Note Go does not have the binary not (~) operator Java does. Use the exclusive-or operator instead. For example:
func not32(x uint32) uint32 {
       return x ^ 0XFF_FF_FF_FF
}
func not64(x uint64) uint64 {
       return x ^ 0XFF_FF_FF_FF_FF_FF_FF_FF
}
or:
func not32(x uint32) uint32 {
       y := int32(-1)
       return x ^ uint32(y)
}
func not64(x uint64) uint64 {
       y := int64(-1)
       return x ^ uint64(y)
}
when run by
fmt.Printf("%X ", not32(10))
fmt.Printf("%x ", not64(10))
produces (note case difference)
FFFFFFF5
fffffffffffffff5

Go Built-in Functions

Go has several built-in functions, summarized in Table 5-3, for access to common behaviors. These functions in general are generic (or overloaded) in that they work on different data types. Java generally has type-specific methods that perform similar behavior.

Note that the Go built-in function names are not reserved keywords; the names may be used for other purposes (possibly hiding the built-in function).
Table 5-3

Java and Go Common Function Comparison

Java

Go

Purpose

.length, .length(), .size(), ...

len(...)

Get the length of a string, array, slice, map, channel

Varies per collection type

cap(...)

Get the capacity of a slice, map, channel; for some collections, the cap and len are the same

new . . . or factory method

make(...) or new(...) or &<structureType>{}

Create (and for make initialize) a collection or structure; new returns a pointer to the allocated memory; for new no constructor call done in Go

System.arraycopy

copy(...)

Copies/moves array elements between same/different arrays

Varies per collection type

delete(...)

Remove element from a map; generally used as a statement

Not in Java; some types have methods to do this

close(...)

Close a channel; generally used as a statement

(<type>)...

<type>(...)

Covert the parameter to the specified type (i.e., a cast)

throw <throwable>

panic(...)

Raise a panic; can send any type as the panic value, but sending an error instance is preferred; generally used as a statement; avoid using panic(nil)

try/catch

v := recover()

Catch a panic. Typically used in a deferred function

Varies per collection type; often add()

append(...)

Appends values to a slice; reallocate the slice if needed; should assign result to input slice

Not in Java

complex(...)

Make a complex value

Not in Java

real(...)

Get the real part of a complex value

Not in Java

imag(...)

Get the imaginary part of a complex value

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.23.30