Home > Backend Development > Golang > How to write interface in go language

How to write interface in go language

王林
Release: 2023-01-13 00:21:40
Original
2723 people have browsed it

The interface definition method in go language: [type interface_name interface {method_name1 [return_type]}]. An interface defines all common methods. Any other type that implements these methods will implement this interface.

How to write interface in go language

The operating environment of this article: windows10 system, Go 1.11.2, thinkpad t480 computer.

The Go language provides another data type, the interface, which defines all common methods together. Any other type that implements these methods will implement this interface.

Example:

/* 定义接口 */
type interface_name interface {
   method_name1 [return_type]
   method_name2 [return_type]
   method_name3 [return_type]
   ...
   method_namen [return_type]
}

/* 定义结构体 */
type struct_name struct {
   /* variables */
}

/* 实现接口方法 */
func (struct_name_variable struct_name) method_name1() [return_type] {
   /* 方法实现 */
}
...
func (struct_name_variable struct_name) method_namen() [return_type] {
   /* 方法实现*/
}
Copy after login

Example:

package main

import (
    "fmt"
)

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type IPhone struct {
}

func (iPhone IPhone) call() {
    fmt.Println("I am iPhone, I can call you!")
}

func main() {
    var phone Phone

    phone = new(NokiaPhone)
    phone.call()

    phone = new(IPhone)
    phone.call()

}
Copy after login

In the above example, we defined an interface Phone, which has a method call(). Then we defined a Phone type variable in the main function and assigned it to NokiaPhone and IPhone respectively. Then call the call() method, the output result is as follows:

I am Nokia, I can call you!
I am iPhone, I can call you!
Copy after login

Related recommendations: golang tutorial

The above is the detailed content of How to write interface in go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template