[转载]Go 和 Java 的 15 个主要差异
Go vs. Java: 15 main differences
The following Java code, adapted from Effective Java, implements an immutable class representing a complex number.
The same program written in idiomatic Go would consist of two separate packages.
Note that in this case Go uses struct values where Java uses references to objects. Also, the
hashCode methods are omitted since Go already defines equality for structs with comparable fields.
Strings are provided by the language; a string behaves like a slice of bytes, but is immutable.
Hash tables are provided by the language. They are called maps.
Pointers and references
Go offers pointers to values of all types, not just objects and arrays. For any type
T, there is a corresponding pointer type
*T, denoting pointers to values of type
Arrays in Go are values. When an array is used as a function parameter, the function receives a copy of the array, not a pointer to it. However, in practice functions often use slices for parameters; slices are references to underlying arrays.
Certain types (maps, slices, and channels) are passed by reference, not by value. That is, passing a map to a function does not copy the map; if the function changes the map, the change will be seen by the caller. In Java terms, one can think of this as being a reference to the map.
Go allows methods on any type; no boxing is required. The method receiver, which corresponds to
thisin Java, can be a direct value or a pointer.
Go provides two access levels, analogous to Java’s public and package-private. Top-level declarations are public if their names start with an upper-case letter, otherwise they are package-private.
Learn more: Functional programming in Go [case study].
Learn more: Concurrent programming in Go [tutorial].
Go does not support implicit type conversion. Operations that mix different types require an explicit conversion. Instead Go offers Untyped numeric constants with no limits.
Go does not support function overloading. Functions and methods in the same scope must have unique names. For alternatives, see Optional parameters and method overloading.
Go has some built-in generic data types, such as slices and maps, and generic functions, such as append and copy. However, there is no mechanism for writing your own generic functions. For alternatives, see Generics (alternatives and workarounds).
Strangely enough, Go has built-in support for complex numbers.
It’s the least used feature of the language. By far.
discusses some main reasons why Go can make it easier (than Java or Python) to write correct, clear and efficient code.