[Go for Java programmers] Go programming for Java developers 3

Source: Internet
Author: User
Document directory
  • Method
  • Interface
  • Anonymous domain
  • Type assertions
Go programming for Java developers

The original English text is here www. Nada. kth. se /~ Snilsson/go_for_java_programmers

Synchronized to www.waylau.com

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

=================================================== ==========.

Slices)

Slice is a conceptual structure that contains three fields: pointer, length, and capacity of an array. Slice support[]Operator to access the elements of the underlying array. Built-inlenThe length of the slice returned by the function. Built-incapFunction returns the slice capability.

Given an array or another slicea[i:j]Create a new slice. The newly created slice pointsa, From IndexiStart and end the indexjBefore. Its length isj - i. IfiOmitted. The Slice starts from 0. IfjOmitted, sliced inlen(a)End. New slice andaPoint to the same array. That is, the elements of the new slices after the changes areaYes. The capacity of the new slice is simple.aMinusi. The size of the array is the length of the array.

var s []intvar a [10]ints = a[:]  // short for s = a[0:len(a)]

If you create a value of the type[100]byte(100 bytes, maybe an array of buffers). If you want to pass it to the function without copying it, then the parameter declaration type of the Function[]byteAnd pass in the array slices. Slice can also be usedmake(As described below ).

Slice combination adopts built-inappendFunction, JavaArrayListProvides the same functions.

s0 := []int{1, 2}s1 := append(s0, 3)      // append a single elements2 := append(s1, 4, 5)   // append multiple elementss3 := append(s2, s0...)  // append a slice

The Slice syntax can also be used on strings. It returns a new string whose value is the substring of the original string.

Make function

Map and channel values must be allocated using the built-in Functionmake. For example, calling map and channel values must use built-in functionsmake. For example

make(map[string]int)

map[string]intReturns a new value type. Relativenew,makeThe actual object instead of an address is returned. This is the same fact. Map and channel are reference types.

For map, the make function regards the capacity as an optional second parameter. For a channel, there is an optional second parameter to set the channel buffer capability. The default value is 0 (no buffer ).

makeThe function can also be used to allocate a slice. In this case, it allocates memory to the basic array and returns a slice that references it. The number of elements in the slice is a required parameter. The second parameter is the slice capacity.

m := make([]int, 10, 20)  // Same as new([20]int)[:10]
Methods and interface methods

The method looks like a normal function definition, but it hasCycler(Recipient ). Extends er is similar to this reference in Java instance methods.

type MyType struct { i int }func (p *MyType) Get() int {    return p.i}var pm = new(MyType)var n = pm.Get()

This declares a methodGetAndMyTypeAssociated. Receiver is namedpIn the function body.

Name typeTo define the method. If you convert values of different types, new values will have new types instead of old ones.

You can define a built-in type method and use the new naming type declaration. The new and built-in types are different.

type MyInt intfunc (p MyInt) Get() int {    return int(p)  // The conversion is required.}func f(i int) {}var v MyIntv = v * v          // The operators of the underlying type still apply.f(int(v))          // int(v) has no defined methods.f(v)               // INVALID
Interface

The Go interface is similar to a Java interface, but can be considered as a method to implement this interface to provide any type of Go interface naming. Explicit statements are unnecessary.

The interface is as follows:

type MyInterface interface {    Get() int    Set(i int)}

SinceMyTypeAlready existsGetMethod, we can makeMyTypeAdd

func (p *MyType) Set(i int) {    p.i = i}

Now anyMyInterfaceAs a parameter, the receiving type is*MyTypeVariable

func GetAndSet(x MyInterface) {}func f1() {    var p MyType    GetAndSet(&p)}

In Java terminology*MyTypeDefinitionSetAndGetEnable*MyTypeAutomatically implementedMyInterfaceInterface. This type can meet multiple interfaces. This is a duck type.

"When you see a bird walking like a duck, swimming like a duck, or screaming like a duck, this bird can be called a duck ."

James Whitcomb Riley

Anonymous domain

Anonymous domains can be used to implement something similar to a Java subclass.

type MySubType struct {    MyType    j int}func (p *MySubType) Get() int {    p.j++    return p.MyType.Get()}

MySubTypeEffective implementation is likeMyTypeChild type.

func f2() {    var p MySubType    GetAndSet(&p)}

SetThe method is inherited fromMyTypeBecause the method associated with the anonymous domain is changed to the method of the closed type. In this case, because
MySubType
There is an anonymous domainMyTypeType, soMyTypeE method also becomesMySubType.GetMethod is overwritten,SetMethod is inherited.

This is not exactly the same as the subclass in Java. When a method of an anonymous domain is called, its receiver is the anonymous domain, rather than the surrounding struct. In other words, methods in the anonymous domain are not dynamically scheduled. If you want to implement dynamic method search equivalent to Java, use the interface.

func f3() {    var v MyInterface    v = new(MyType)    v.Get()  // Call the Get method for *MyType.    v = new(MySubType)    v.Get()  // Call the Get method for *MySubType.}
Type assertions

A type assertion can be used to convert a variable with an interface type to a variable with a different interface type. This is executed dynamically at runtime. Unlike Java, there is no need to declare the relationship between the two interfaces.

type Printer interface {    Print()}func f4(x MyInterface) {    x.(Printer).Print()  // type assertion to Printer}

ConvertPrinterIt is completely dynamic. As longx(The actual type of the value stored in X)Dynamic typeDefinesPrintMethod.

============================== Not complete To be continued...

=

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.