"Go for Java Programmers" Go programming for Java Developers 1

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go programming for Java Developers

The English text is in this www.nada.kth.se/~snilsson/go_for_java_programmers

Sync to http://blog.csdn.net/kkkloveyou/article/details/8256649

Http://bbs.gocn.im/thread-52-1-1.html

======================= the following body ========================.

  • Hello Stack (example)
  • Conceptual differences
  • Syntax
  • Constants
  • Structs
  • Pointers
  • Slices
  • Making values
  • Methods and Interfaces
  • Errors
  • Panic and recover
  • Goroutines and Channels
  • Concurrency (example)

This article is intended to help Java developers quickly master the go language.

Start with an example that can easily be recognized by all Java programmers, then give a detailed description of the go framework, and finally use an example to illustrate that the go structure does not correspond directly to Java.

Hello Stack (example of a stack)

In order to lift your appetite, we use a very, very perfectly formed and customary example to correspond to this Stack.java program.

Packet collection implements the build stack. The package collection//0 value stack is an empty stack that is ready to be used. Type stack struct {    data []interface{}}// The Push function adds x to the top of the stack. Func (S *stack) Push (x interface{}) {    s.data = append (S.data, x)}//the POP function removes and returns the top element of the stack.//In the POP function execution on the empty stack, Will be alerted by a runtime error. Func (S *stack) Pop () interface{} {    I: = Len (s.data)-1    Res: = S.data[i]    s.data[i] = nil  Avoid memory leaks    S.data = s.data[:i]    return res}//size function returns the number of elements in the stack func (S *stack) Size () int {    return len (S.data)}
Stack.go
  • Before a top-level statement appears, a direct comment is a document comment. They are plain text.
  • For the declaration, you write the name behind the type.
  • structCorresponds to a class in Java, but the struct composition is not a method but only a variable.
  • The T interface{} type corresponds Object to Java. In go it is implemented by all types, not just reference types.
  • The code snippet (s*Stack) declares a method that the receiver s corresponds to in Java this .
  • The operator := declares and initializes a variable. Its type can be deduced from an initialization expression.

Here is a Hello World program that demonstrates how to use collection.Stack the abstract data type.

Package Collection_testimport (    collection "."    ) FMT ") func Example () {    var s collection. Stack    S.push ("World")    s.push ("Hello,") for    s.size () > 0 {        fmt. Print (S.pop ())    }    fmt. PRINTLN ()    //output: Hello, world}
Example_test.go

Conceptual differences

  • The go constructor has no classes. Go uses structs and interfaces instead of instantiation methods, class inheritance mechanisms, and dynamic method lookups. Also available for Java using generic interfaces
  • go provides all types The value of the pointer, not just the object and the array. For any type of t , there is a corresponding pointer type *t indicates pointer to type t .
  • Go allows any type to have a method without a boxed restriction method receiver, which corresponds to a this direct value or a pointer in Java.
  • The array in Go is the value. When an array is treated as an argument to a function, the function receives a copy of the array instead of its pointer. In practice, however, the function often uses slices as a parameter; Slices references the underlying array.
  • The language provides a string, a string behaves like a byte slice, but is immutable.
  • The hash table in the language is called maps.
  • The language provides a separate running thread for Goroutines and communication channels between them channels.
  • Some types (maps, slices, and channels) are passed by reference, not values. That is, passing a map to a function instead of copying a map, if the function modifies the map, the caller will see the change. In Java terminology, it can be thought of as a reference to a map.
  • Go provides two levels of access to the Java public and the private of the package. If it is named uppercase, it starts with the highest level of public, and vice versa is the private of the package.
  • To replace the exception mechanism in Java, go takes the type error value to represent an event, such as the end of the file, and the runtime's panics to indicate runtime errors, such as an array out of bounds.
  • Go does not support implicit type conversions. Blending with different types of operations requires an explicit conversion.
  • Go does not support function overloading. Functions and methods within the same scope must have a unique name.
  • Go uses nil A pointer that represents an invalid, similar to Java usage null .

Syntactic

Statement

The declaration is the opposite of Java. You write the name after the type, and the type declaration is easier to read from left to right

The go is corresponding to Java
var v1 int int v1;
var v2 *int integer v2;
var v3 string string v3 = "";
var V4 [10]int int[] v4 = new INT[10]; V4 is a value in go.
var V5 []int int[] V5;
var V6 *struct {a int} C V6; Given:class C {int A;}
var v7 map[string]int hashmap<string,integer> V7;
var V8 func (a int) int F V8; Given:interface F {int f (int a);}

The general form of a declaration is a keyword followed by the name of the object being declared. The keyword is const ,, type var , or func . You can also use a keyword, followed by a series of declarations in parentheses.

var (    n int    x float64)

When declaring a function, you must provide the name of each parameter, or do not provide the name of any parameter, you cannot provide some but omit some other name. You can combine several names of the same type:

Func f (i, j, K int, S, t string)

A variable can be initialized at the time of declaration. When you do this, the type of the specified variable is allowed, but is not required. When a type is not specified, the default is the type of the initialization expression.

var v9 = *v2

If a variable is not initialized immediately, the type must be set. In that case, it will be implicitly initialized with a value of 0 of the type zero(, 0 nil ,, "" etc.). Go does not have uninitialized variables.

Short statement

In the function, a short declarative syntax is := represented.

V10: = V1

This is equivalent to

var v10 = V1

function type

In go, the function is a one-class citizen. The function type of go represents a set of all functions that have the same parameters and return types.

Type BINOP func (int, int) Intvar op binopadd: = Func (i, j int) int {return i + j}op = Addn = OP (+-)  //n = 100 + 200

Multiple allocations

Go allows multiple allocations. The expression on the right is evaluated and then assigned to any left operand.

I, j = j, I  //Exchange I and J.

A function can have multiple return values, represented by a list in parentheses. The returned value can be stored as assigned to a list of variables.

Func f () (i int, pj *int) {...} V1, V2 = f ()

Blank identifiers

A blank identifier provides a way of ignoring the return value of a multivalued expression, denoted by an underscore character: The blank identifier, represented by the underscore character, provides a ways to ignore Values returned by a multi-valued expression:

V1, _ = f ()  //ignores the second value returned by F ().

Semicolons and formatting

In order to eliminate unnecessary concerns about semicolons and formatting, you may be able gofmt to use the program to write standard go-style code, although this style looks odd, but eventually becomes as comfortable as other language styles.

The code in Go has a lot of semicolons appearing in practice. Strictly speaking, all declarations of go are terminated with semicolons. But go will no doubt insert a semicolon at the end of each non-blank line, unless it's not finished yet. The consequence of this is that, in some cases, go does not allow a break. For example, you might write like this:

Func g () {            ///invalid; " {"It should be in the front row."} }

g()a semicolon is inserted in the back so that he is like a function declaration rather than a function defined similar, you cannot write:

if n = = 0 {}else {       ///invalid; "Else {" should be in the previous line. }

} A semicolon is inserted in the back and else front, resulting in a syntactic error.

=================== to be Continued ... ==========

=================== Reprint Annotated Source =============


2012-12-4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.