search
HomeBackend DevelopmentGolangCan go language develop interfaces?

Can go language develop interfaces?

Dec 15, 2022 pm 06:49 PM
golanginterfacego language

Go language can develop interfaces. The interface in the Go language is the signature of a set of methods. It is an important part of the Go language. What the interface does is like defining a specification or protocol. Each implementing party only needs to implement it according to the protocol. The interface keyword is used in the go language to define the interface. The syntax is "type interface type name interface{method name 1 (parameter list 1) return value list 1 method name 2 (parameter list 2) return value list 2...}".

Can go language develop interfaces?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Interface should be a familiar concept to us. It is widely used in various development languages. For programmers like us who are more familiar with Java, interfaces are more familiar. The following Let’s take a look at how interfaces are used in the Go language and the role they play in daily development.

Concept

The interface in the Go language is the signature of a set of methods. It is an important part of the Go language. What the interface does is like defining a specification. Or agreement, each implementing party only needs to implement it according to the agreement.

Interface is a type

Interface type is an abstraction and generalization of the behavior of other types. It does not care about specific implementation details. This abstract method can make our functions more flexible. .

Interface definition

type 接口类型名 interface{
    方法名1( 参数列表1 ) 返回值列表1
    方法名2( 参数列表2 ) 返回值列表2
    …
}

In the go language we use the interface keyword to define the interface.

Interface implementation conditions

If the method set of any type T is a superset of the method set of an interface type, then we say that type T implements the interface.

The implementation of the interface is implicit in the Go language, which means that the implementation relationship between the two types does not need to be reflected in the code. There is no keyword similar to the implements in Java in the Go language. Go The compiler will automatically check the implementation relationship between two types when needed. After the interface is defined, it needs to be implemented so that the caller can correctly compile and use the interface.

The implementation of the interface needs to follow two rules to make the interface available:

1. The methods of the interface are in the same format as the type method that implements the interface. Just add a method consistent with the interface signature in the type. Implement this method. The signature includes the name, parameter list, and return parameter list of the method. In other words, as long as any item in the name, parameter list, and return parameter list of the method in the implemented interface type is inconsistent with the method to be implemented by the interface, then this method of the interface will not be implemented.

package main

import "fmt"

type Phone interface {
	Call()
	SendMessage()
}

type HuaWei struct {
	Name  string
	Price float64
}

func (h *HuaWei) Call() {
	fmt.Printf("%s:可以打电话",h.Name)
}

func (h *HuaWei) SendMessage() {
	fmt.Printf("%s:可以发送短信",h.Name)
}

func main() {

	h := new(HuaWei)
	h.Name="华为"
	var phone Phone
	phone = h
	phone.SendMessage()
}

When a type cannot implement an interface, the compiler will report an error:

a. Errors caused by inconsistent function names

b. Errors caused by inconsistent method signatures to implement functions

2. All methods in the interface are implemented. When there are multiple methods in an interface, only if these methods are implemented can the interface be compiled and used correctly

func (h *Xiaomi) Call() {
	fmt.Printf("%s:可以打电话",h.Name)
}

func main() {
	h := new(Xiaomi)
	h.Name="小米"
	var phone Phone
	phone = h
	phone.SendMessage()
}

Can go language develop interfaces?

When the Xiaomi type only implements one method in the interface, a compilation error will be reported when we use it.

The relationship between types and interfaces

A type implements multiple interfaces

A type can implement multiple interfaces, and the interfaces are independent of each other and do not know the implementation of each other.

For example, a dog can move and be called

package main

import "fmt"

type Move interface {
	move()
}
type Say interface {
	say()
}
type Dog struct {
	Name string
}

func (d *Dog) move()  {
	fmt.Printf("%s会动\n", d.Name)
}
func (d *Dog) say()  {
	fmt.Printf("%s会叫汪汪汪\n", d.Name)
}

func main() {
	var m Move
	var s  Say
	d:=&Dog{
		Name: "旺财",
	}
	m = d
	s=d
	m.move()
	s.say()
}

Multiple types implement the same interface

In Go language Different types can also implement the same interface. First we define a Mover interface, which requires a move method.

type Mover interface {
    move()
}

For example, dogs can move, and cars can also move. You can use the following code to achieve this relationship:

type dog struct {
    name string
}

type car struct {
    brand string
}

// dog类型实现Mover接口
func (d dog) move() {
    fmt.Printf("%s会跑\n", d.name)
}

// car类型实现Mover接口
func (c car) move() {
    fmt.Printf("%s速度70迈\n", c.brand)
}

At this time, we can treat dogs and cars as one moving object in the code To deal with it, you no longer need to pay attention to what they are, you only need to call their move method.

func main() {
        var x Mover
        var a = dog{name: "旺财"}
        var b = car{brand: "保时捷"}
        x = a
        x.move()
        x = b
        x.move()
    }

Empty interface

Empty interface: interface{}, does not contain any methods. Because of this, any type implements the empty interface, so the empty interface can be stored Any type of data.

fmt The Print series of functions under the package, most of their parameters are empty interface types, it can also be said to support any type

func Print(a ...interface{}) (n int, err error)
func Println(format string, a ...interface{}) (n int, err error)
func Println(a ...interface{}) (n int, err error)

The empty interface is used as The value of map

// 空接口作为map值
    var studentInfo = make(map[string]interface{})
    studentInfo["name"] = "李白"
    studentInfo["age"] = 18
    studentInfo["married"] = false
    fmt.Println(studentInfo)

Type inference

The empty interface can store any type of value, so how do we get the specific data it stores?

Interface value

The value of an interface (referred to as interface value) is composed of a specific type and the value of the specific type.

These two parts are called the dynamic type and dynamic value of the interface respectively.

If you want to judge the value in the empty interface, you can use type assertion. Its syntax format is:

x.(T)

Among them:

  • x: means A variable of type interface{}

  • T: represents the type that the assertion x may be.

该语法返回两个参数,第一个参数是x转化为T类型后的变量,第二个值是一个布尔值,若为true则表示断言成功,为false则表示断言失败。

func main() {
    var x interface{}
    x = "ms的go教程"
    v, ok := x.(string)
    if ok {
        fmt.Println(v)
    } else {
        fmt.Println("类型断言失败")
    }
}

 上面的示例中如果要断言多次就需要写多个if判断,这个时候我们可以使用switch语句来实现:

func justifyType(x interface{}) {
    switch v := x.(type) {
    case string:
        fmt.Printf("x is a string,value is %v\n", v)
    case int:
        fmt.Printf("x is a int is %v\n", v)
    case bool:
        fmt.Printf("x is a bool is %v\n", v)
    default:
        fmt.Println("unsupport type!")
    }
}

因为空接口可以存储任意类型值的特点,所以空接口在Go语言中的使用十分广泛。

总结

关于接口需要注意的是,只有当有两个或两个以上的具体类型必须以相同的方式进行处理时才需要定义接口。不要为了接口而写接口,那样只会增加不必要的抽象,导致不必要的运行时损耗。

【相关推荐:Go视频教程编程教学

The above is the detailed content of Can go language develop interfaces?. 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
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools