Introduction to the interface of golang
The following column golang tutorial will introduce you to the interface of golang. I hope it will be helpful to friends in need!
#In Go language, interface is a type, an abstract type.
Definition of interface
Definition format:
type 接口类型名 interface{ 方法名1( 参数列表1 ) 返回值列表1 方法名2( 参数列表2 ) 返回值列表2 … }
When naming Go language interfaces, er is usually added after the word. It is best for the interface name to be Highlight the type meaning of the interface.
Interface implementation
As long as an object implements all the methods in the interface, then it implements the interface.
Different types in Go language can implement the same interface. (In the example, both dog and cat implement the Animal interface)
//定义一个Animal接口// Animal 是一个动物接口,实现move()和say()方法type Animal interface { move() say() }//定义dog结构体type dog struct { name string }//定义cat结构体type cat struct { name string }//dog实现move方法func (d dog) move() { fmt.Printf("%s会跑\n",d.name) }//dog实现say方法func (d dog) say() { fmt.Printf("%s会叫汪汪汪\n",d.name) }//cat实现move方法func (c *cat) move() { fmt.Printf("%s会跑\n",c.name) }//cat实现say方法func (c cat) say() { fmt.Printf("%s会叫喵喵喵\n",c.name) }func main() { var a Animal //声明一个Animal类型的a //实例化一个dog结构体 d := dog{name:"旺财"} fmt.Printf("%T\n", d) //main.dog d.move() //旺财会跑 d.say() //旺财会叫汪汪汪 a = d // 接口是一种类型,一种抽象的类型。 fmt.Println(a) //{旺财} //实例化一个cat结构体 c := cat{name:"蓝猫"} c.move() //蓝猫会跑 c.say() //蓝猫会叫喵喵喵 }
Polymorphism
GO language simulates polymorphism through interfaces.
Relationship between types and interfaces
A type can implement multiple interfaces at the same time, and the interfaces are independent of each other and do not know the implementation of each other.
Different types in Go language can implement the same interface.
Interface nesting
New interfaces can be created through nesting between interfaces.
//定义speaker接口type speaker interface { speak() }//定义mover接口type mover interface { move() }// 接口嵌套type animal interface { speaker mover }//定义cat结构体type cat struct { name string }//cat是值类型接收者func (c cat) speak() { fmt.Println("喵喵喵") }func (c cat) move() { fmt.Println("猫会动") }func main() { var x animal x = cat{name: "花花"} x.move() //猫会动 x.speak() //喵喵喵 }
Empty interface
Empty interface definition
Empty interface refers to an interface that does not define any methods. Variables of empty interface type can store variables of any type.
//空接口func main() { var x interface{} x = 100 //int类型 fmt.Println(x) //100 x = "ares" //string类型 fmt.Println(x) //ares x = struct { //结构体类型 name string }{name:"ares"} //结构体赋值 fmt.Println(x) //ares }
Empty interface application
Empty interface can be used as a parameter of a function or the value of a map.
//空接口func showType(a interface{}) { fmt.Printf("type:%T\n", a) }func main() { //空接口作为函数的参数 showType(100) //type:int showType("ares") //type:string //定义一个值为空接口的map var stu = make(map[string]interface{},100) stu["ares"] = 100 stu["ares1"] = "男" fmt.Println(stu) //map[ares:100 ares1:男] //map,key是字符串,value是任意类型 map1 := make(map[string]interface{}) map1["name"] = "ares" map1["age"] = 18 map1["id"] = 1 map1["friend"] = struct { name string age int }{"jay", 33} fmt.Println(map1) //map[age:18 friend:{jay 33} id:1 name:ares] }
Interface nesting
is similar to inheritance.
type A interface { test1() }type B interface { test2() }type C interface { A B test3() }type Cat struct { //如果要实现接口c,需要将接口a和接口b中的方法一起实现 }func (c Cat) test1() { fmt.Println("test1...") }func (c Cat) test2() { fmt.Println("test2...") }func (c Cat) test3() { fmt.Println("test3...") }func main() { var cat = Cat{} cat.test1() //test1... cat.test2() //test2... cat.test3() //test3... //将cat赋值接口A类型,则只能使用test1方法 var cat1 A = Cat{} cat1.test1() //test1... //将cat赋值接口B类型,则只能使用test2方法 var cat2 B = Cat{} cat2.test2() //test2... }
Type assertion
Syntax:
x.(T)
x: Represents a variable of type interface{}
T : Indicates the type that assertion x may be
If true, it indicates that the assertion is successful, and if it is false, it indicates that the assertion fails.
//类型断言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) case *string: fmt.Printf("x is a point指针 is %v\n", v) case struct{}: fmt.Printf("x is a struct is %v\n", v) default: fmt.Println("unsupport type!") }}func main() { justifyType(100) //x is a int is 100 justifyType("ares") //x is a string,value is ares justifyType(false) //x is a bool is false x := "ares" justifyType(&x) //x is a point指针 is 0xc000094010 justifyType(struct {}{}) //x is a struct is {} justifyType([]int{123}) //unsupport type! }
Value receiver and Pointer receiverThe difference between implementing interfaces
If the receiver is a pointer type, the value cannot be Pass it in.
//定义animal接口type animal interface { speak() move() }//定义cat结构体type cat struct{ name string }//定义dog结构体type dog struct{ name string }//值接收者 func (c cat) speak() { fmt.Printf("%s会叫喵喵喵\n",c.name) } func (c cat) move() { fmt.Printf("%s会动\n",c.name) } //指针接收者func (d *dog) speak() { fmt.Printf("%s会叫汪汪汪\n",d.name) }func (d *dog) move() { fmt.Printf("%s会动\n",d.name) }func main() { var c1 animal lm := cat{name:"蓝猫"} c1 = lm //因为实现animal接口的是cat值类型,所以可以直接赋值 c1.move() //蓝猫会动 c1.speak() //蓝猫会叫喵喵喵 var c2 animal jm := &dog{name:"金毛"} //现animal接口的是*dog类型,所以必须要通过&来取值 c2 = jm c2.move() //金毛会动 c2.speak() //金毛会叫汪汪汪 }
The above is the detailed content of Introduction to the interface of golang. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.
