Golang Methods and Interfaces

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

In programming languages, the concepts of methods and functions need to be clear. A function refers to a encapsulated block of code that we can call directly and return the result. The method is actually a function, except that the method needs to be bound to an object. Golang does not have a class concept, but there are concepts of methods and interfaces.

Method

Method recipient

The method receiver is a special parameter, and after assigning this parameter to the function, the function becomes the method. This feature is somewhat like the extension method in Kotlin and C #, after defining a method with a receiver, the receiver type is like defining this method, and we can invoke the method directly on that type. This is functionally, and the concept of object-oriented is very similar.

For example, a car structure is defined, and a recipient method is defined. You can then invoke this method in an object-oriented manner.

func Method() {    //方法接收者    car := Car{id: 1}    car.beep()}type Car struct {    id int}func (car Car) beep() {    fmt.Printf("Car %v beeps", car.id)}

The receiver method also has some limitations, which is the difference between it and the extension method. the receiver type of the recipient method must be defined in the same package as the recipient method. so many non-custom types, as well as basic types, cannot be the recipient type. Of course, you can also opportunistic, in their own package to re-name these types can be.

//把基本类型重新定义一下,就可以当做接收者类型了type MyString stringfunc (str MyString) hello() {    fmt.Println("hello" + str)}

Pointer recipient

The type of the receiver can be a pointer, and if you want to modify the recipient's properties in the recipient method, the pointer type is required. The following code Car adds two methods to the struct, the first because there is no pointer type, so the value in the original struct is not modified, and the second method modifies the car's ID.

func (car Car) beep() {    fmt.Printf("Car %v beeps", car.id)}func (car Car) changeId() {    car.id += 1}func (car *Car) changeRealId() {    car.id += 1}

Interface

It sounds strange that if Golang has no type, why does it have an interface concept? Let's take a look at how Golang solves these problems.

Defining interfaces

In Golang, an interface is a set of method signatures. An interface is defined below.

type ICar interface {    beep()    drive(driver string)}

Implementing interfaces

In the Golang, there is actually no "implementation interface" of the saying. Interfaces are implicitly implemented in Golang, meaning that we do not need implements these keywords. As long as a receiver method of a type is consistent with the method defined in the interface, Golang thinks that this type implements the interface. The following is a simple example.

func Interface() {    car := MyCar{id: 1}    var icar ICar = car    icar.beep()    icar.drive("yitian")}type ICar interface {    beep()    drive(driver string)}type MyCar struct {    id int}func (car MyCar) beep() {    fmt.Printf("car %v beeps\n", car.id)}func (car MyCar) drive(driver string) {    fmt.Printf("%v drives car %v\n", driver, car.id)}

Null interface

An interface that is not defined by any method is an empty interface. According to the Golang concept, an empty interface is implicitly implemented by any type, so an empty interface can accommodate any type.

//空接口可以作为任何类型使用type Everything interface {}var e Everything = "123"fmt.Println(e)

Type refinement

Defining and implementing an interface is a type-generalization process in which we erase the type-specific parts and make the public part of the type uniformly available. However, sometimes it is necessary to turn an interface object into the original concrete class, allowing us to get more specific behavior.

Now look at the Golang, how this thing should be done. Use the type defined above again. You can see that the parentheses in the C language are strongly different, and the syntax for the type is in Golang .(T) .

//特化类型myCar := icar.(MyCar)//myCar是MyCar类型变量myCar.beep()

This syntax also has a version that carries a successful flag t, ok := i.(T) . When the success flag is true, it means that the interface is successfully converted to a specific type, otherwise the interface is not an instance of a specific type.

If you want to make multiple judgments, you can use switch statements. Here is an example.

func testType(i interface{}) {    switch i.(type) {    case string:        fmt.Printf("%v is string\n", i)    case int:        fmt.Printf("%v is int\n", i)    default:        fmt.Printf("%v is interface{}\n", i)    }}

Multiple calls to this method can be seen for different types, and the method will return different results.

//类型检测testType("abc")testType(123)testType(nil)
Related Article

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.