Golang Classes and structs

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

Golang Structures and Classes

There is no explicit object-oriented argument in the Golang, and it is true that structs can be compared to classes in other languages.

class declaration

type Poem struct {    Title  string    Author string    intro  string}

This declares a class in which there is no public, protected, private declaration. Golang uses a different approach to access the property: The first letter of the property is capitalized and can be accessed in other packages, otherwise it is only accessible in this package. This is also true of the Declaration and method of the class.
Attention:

p1 := &Poem{        "zhangsan",        25,        []string{"lisi", "wangwu"},    }

If an array is included in use, the instantiation of the struct needs to be added to the type above if the type of intro is []string.

class method declaration

func (poem *Poem) publish() {    fmt.Println("poem publish")}

Or

func (poem Poem) publish() {    fmt.Println("poem publish")}

Unlike other languages, Golang declares that the method is consistent with the normal method, but adds a declaration such as poem poem after Func. the difference between adding and not adding * is that one is passing a pointer object and one is passing a value object.

The difference between passing pointers and objects

type T struct {    Name string}func (t T) M1() {    t.Name = "name1"}func (t *T) M2() {    t.Name = "name2"}

The recipient of M1 () is a value type T, the recipient of M2 () is a value type *t, and two methods change the name value.

The following declares a variable of type T and calls M1 () and M2 ().

    t1 := T{"t1"}    fmt.Println("M1调用前:", t1.Name)    t1.M1()    fmt.Println("M1调用后:", t1.Name)    fmt.Println("M2调用前:", t1.Name)    t1.M2()    fmt.Println("M2调用后:", t1.Name)

The output is:

Before M1 call: T1
After M1 call: T1
Before M2 call: T1
After M2 call: name2

Let's guess what go will do with it.

Let's make a pact: the receiver can be thought of as the first parameter of the function, that is, func M1 (T-t), Func M2 (t *t). Go is not an object-oriented language, so it may be biased to understand that it looks like object-oriented syntax.

When calling T1. M1 () is equivalent to M1 (T1), and both the argument and the row parameter are of type T, which is acceptable. At this point the T in M1 () is only a copy of the value of T1, so the modification of M1 () does not affect T1.

When calling T1. M2 () = M2 (T1), which is to pass the T type to the *t type, go may take the T1 address into it: M2 (&T1). So the modification of M2 () can affect T1.

anonymous struct

p := struct {    Name string    Gender string    Age uint8}{"Robert", "Male", 33}

The most useful use of an anonymous struct is to create a structure internally temporarily to encapsulate the data without having to formally declare the rules for it.

Instantiating an Object

There are several ways of instantiating an object

poem := &Poem{}poem.Author = "Heine"poem2 := &Poem{Author: "Heine"}poem3 := new(Poem)poem3.Author = "Heine"poem4 := Poem{}poem4.Author = "Heine"poem5 := Poem{Author: "Heine"}

The property value can be initialized when instantiated, default to system default if not indicated

Add & Symbol and new is a pointer object, no is a value object, this is inconsistent with PHP, Java, when passing the object to decide whether to pass the pointer or value.

Tips: Passing pointers is not a good deal when objects are small.

Constructor (create it yourself)

func NewPoem(param string, p ...interface{}) *Poem

Example:

func NewPoem(author string) (poem *Poem) {    poem = &Poem{}    poem.Author = author    return}poem6 := NewPoem("Heine")

Inherited

Specifically, Golang is called a combination (composition).

type Poem struct {    Title  string    Author string    intro  string}type ProsePoem struct {    Poem    Author string}

The poem is declared in the Prosepoem property, which represents the properties and methods that combine poem. Can be called as follows:

prosePoem := &ProsePoem{}prosePoem.author = "Heine"

If there is a conflict in the attribute, the perimeter is the primary, that is, it is overwritten.

type ProsePoem struct {    Poem    Author string}

When accessing author, the default is Prosepoem author, if you need to access the Author property of poem You can use the
ProsePoem.Poem.Author to visit.

prosePoem := &ProsePoem{}prosePoem.Author = "Shelley"prosePoem.Poem.Author = "Heine"fmt.Println(prosePoem)

This can be seen intuitively from the output.

&{{Heine} Shelley}

The inheritance and properties of the method are consistent and are no longer listed here. By combining the words can be very good to achieve multiple inheritance.

Method overloading

A method overload is a class in which you can have the same function name, but their arguments are inconsistent, which is common in Java and C + +. Golang If you try to do this will report a re-declaration (redeclared) error, but the Golang function can declare indeterminate parameters, which is very powerful.

Func (poem *poem) recite (v. ... interface{}) {

fmt.Println(v)

}

where v ... interface{} indicates the indefinite meaning of the parameter, where V is the slice type, FMT. The Println method is also defined in this way. If you want to implement different functions according to different parameters, you need to detect the passed parameters within the method.

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.