search
HomeBackend DevelopmentGolangStarting from scratch: Creation and implementation of Golang interface

Starting from scratch: Creation and implementation of Golang interface

Start from scratch: Creation and implementation of Golang interface

In Golang, an interface is a type that defines behavior. An interface defines a set of methods without providing specific implementations of these methods. An interface is an abstract type through which polymorphism can be achieved, making the program more flexible and extensible. This article will introduce how to create an interface in Golang and implement the specific methods of the interface, and provide code examples to help readers better understand.

1. Create an interface

In Golang, use the keywords type and interface to define an interface. An interface can contain any number of methods, each method consists of a method name, a parameter list, and a return value list. The following is a simple interface definition example:

package main

import "fmt"

// 定义一个接口
type Shape interface {
    Area() float64
    Perimeter() float64
}

In the above example, we define an interface named Shape, which contains two methods Area() and Perimeter() are used to calculate the area and perimeter of the shape respectively.

2. Implement the interface

To implement an interface, you only need to define the methods in the interface on the custom type. The following is an example of implementing the Shape interface:

package main

import "fmt"

// 定义一个矩形类型
type Rectangle struct {
    Width  float64
    Height float64
}

// 实现Shape接口的Area方法
func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

// 实现Shape接口的Perimeter方法
func (r Rectangle) Perimeter() float64 {
    return 2*r.Width + 2*r.Height
}

func main() {
    r := Rectangle{Width: 5, Height: 3}
    fmt.Println("矩形的面积:", r.Area())
    fmt.Println("矩形的周长:", r.Perimeter())
}

In the above code, we define a Rectangle type and implement Shape##Area() and Perimeter() methods of the interface. In the main function, we create a Rectangle object r and call the interface method it implements.

3. Polymorphism

Interfaces can achieve polymorphism in Golang, that is, instances of different types can implement the same interface and call the same method. This makes the program more flexible and scalable. Here is an example of using polymorphism:

package main

import "fmt"

// 定义一个圆形类型
type Circle struct {
    Radius float64
}

// 实现Shape接口的Area方法
func (c Circle) Area() float64 {
    return 3.14 * c.Radius * c.Radius
}

// 实现Shape接口的Perimeter方法
func (c Circle) Perimeter() float64 {
    return 2 * 3.14 * c.Radius
}

func main() {
    r := Rectangle{Width: 5, Height: 3}
    c := Circle{Radius: 2}

    shapes := []Shape{r, c}

    for _, shape := range shapes {
        fmt.Println("面积:", shape.Area())
        fmt.Println("周长:", shape.Perimeter())
    }
}

In the above example, we define a

Circle type and implement the Shape interface #Area() and Perimeter() methods. In the main function, we create a Rectangle object r and a Circle object c, and add them Put it into a slice of type []Shape. Then by traversing the slices and calling the methods of the Shape interface, the effect of polymorphism is achieved. Through the above examples, readers can better understand how to create interfaces in Golang and the specific methods to implement interfaces. Interface is an important feature in Golang, which can help us write more modular, flexible and extensible code. Hope this article can be helpful to readers.

The above is the detailed content of Starting from scratch: Creation and implementation of Golang interface. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
主板aafp是什么接口主板aafp是什么接口Aug 29, 2022 am 10:50 AM

主板上的aafp是音频接口;该接口的功能是启用前面板的“3.5mm”插孔,起到传输音频的作用,aafp跳线基本上由两个部分组成,一部分是固定在主板、硬盘等设备上的,由两根或两根以上金属跳针组成,另一部分是跳线帽,是一个可以活动的组件,外层是绝缘塑料,内层是导电材料,可以插在跳线针上。

cha fan表示什么风扇cha fan表示什么风扇Sep 15, 2022 pm 03:09 PM

“cha fan”表示的是机箱风扇;“cha”是“chassis”的缩写,是机箱的意思,“cha fan”接口是主板上的风扇供电接口,用于连接主板与机箱风扇,可以配合温度传感器反馈的信息进行智能的转速调节、控制噪音。

ioioi是什么接口ioioi是什么接口Aug 31, 2022 pm 04:50 PM

ioioi是指COM接口,即串行通讯端口,简称串口,是采用串行通信方式的扩展接口。COM接口是指数据一位一位地顺序传送;其特点是通信线路简单,只要一对传输线就可以实现双向通信(可以直接利用电话线作为传输线),从而大大降低了成本,特别适用于远距离通信,但传送速度较慢。

link/act是什么接口link/act是什么接口Feb 23, 2023 pm 04:14 PM

link/act是物理数据接口;交换机上的link/act指示灯表示线路是否连接或者活动的状态;通常Link/ACT指示灯用来观察线路是否激活或者通畅;一般情况下,若是线路畅通,则指示灯长亮,若是有数据传送时,则指示灯闪烁。

jbat1是什么接口jbat1是什么接口Jun 23, 2021 pm 01:38 PM

jbat1是主板电2113池放电跳线接口,对于现在市面上常见的主板来说,它们都设计有CMOS的放电跳线,让用户在操作时更加便捷,它也因此成为了CMOS最常见的放电方法。

sata6g是什么接口sata6g是什么接口Sep 14, 2022 am 11:46 AM

sata6g是数据传输速度为“6G/s”的sata接口;sata即“Serial ATA”,也就是串行ATA,是主板接口的名称,现在的硬盘和光驱都使用sata接口与主板相连,这个接口的规格目前已经发展到第三代sata3接口。

dc接口是什么意思dc接口是什么意思Aug 24, 2022 am 10:47 AM

dc接口是一种为转变输入电压后有效输出固定电压接口的意思;dc接口是由横向插口、纵向插口、绝缘基座、叉形接触弹片、定向键槽组成,两只叉型接触弹片定位在基座中心部位,成纵横向排列互不相连,应用于手机、MP3、数码相机、便携式媒体播放器等产品中。

pump fan是什么接口pump fan是什么接口Jun 25, 2021 pm 02:55 PM

pump fan是散热风扇接口。主板上的风扇接口有cpu fun、sys fun、pump fun,对于一般普通用户来说区别不大,一般接哪个都行,而pump fun上的电流更大一点,用于接功率大一点的水冷风扇头。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools