当前位置:网站首页>Go language - Interface
Go language - Interface
2022-06-21 15:38:00 【Crying while learning】
summary
Only methods are defined in the interface , There is no concrete implementation of the method . Method code needs types to implement .
If a structure is defined , To implement the methods in the interface . Then this structure is the implementation of the interface .
- When an interface type object is required , You can use any implementation class object instead of .
- Interface objects cannot call fields of implementation classes .
Function of interface
- The function of the interface is decoupling . When modifying part of the code , Other parts of the code are least affected .
- Interface is the separation of function definition and function implementation .
- Through interface , It can simulate the polymorphism of object-oriented language .
grammar
//1. Defining interfaces
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
...
}
// Defining structure
type struct_name1 struct {
Field name Field type
}
// Implementation interface method
func (variable struct_name1) method_name1(parameter list) (return list) {
Method realization
}
func (variable struct_name1) method_name2(parameter list) (return list) {
Method realization
}Simulate one USB Interface . Realization start() and stop() Method . Two different structures implement mouse and storage ( Of the phenomenon object polymorphic ).
// Interface
type USB interface {
start()
stop()
}
// Mouse structure
type Mouse struct {
name string
}
// Flash memory structure
type FlashDisk struct {
name string
}
// Structure method
func (m Mouse) start() {
fmt.Println(m.name, " The mouse starts to work ...")
}
func (m Mouse) stop() {
fmt.Println(m.name, " The mouse stops working ...")
}
func (f FlashDisk) start() {
fmt.Println(f.name, " Flash memory inserted , You can start using ...")
}
func (f FlashDisk) stop() {
fmt.Println(f.name, " Flash memory unplugged ...")
}
// The test method
func testInterface(usb USB) {
usb.start()
usb.stop()
}
func main() {
mouse1 := Mouse{" Thunder snake super mouse "}
flashDisk1 := FlashDisk{"15TB Super flash "}
testInterface(mouse1)
testInterface(flashDisk1)
var usb USB = Mouse{" Logitech mouse "}
usb.start()
usb.stop()
}
Empty interface
Empty interface : Interfaces that do not contain any methods .
All types implement empty interfaces , Because of this , An empty interface type can store values of any type .
effect : Empty interface types can be defined , Definition array、slice、map, Type is empty interface type . You can store any type of value .
An empty interface type stores values of any type
// Interface
type A interface {
}
// Structure
type Animal struct {
name string
}
type People struct {
name string
age int
}
func main() {
var a1 A = Animal{"minacat"}
var a2 A = People{"liqi", 18}
var a3 A = "aaa"
var a4 A = 555
fmt.Printf("a1 Value :%v, a1 The type of :%T\n", a1, a1)
fmt.Printf("a2 Value :%v, a2 The type of :%T\n", a2, a2)
fmt.Printf("a3 Value :%v, a3 The type of :%T\n", a3, a3)
fmt.Printf("a4 Value :%v, a4 The type of :%T\n", a4, a4)
}
array、slice、map The type definition is an empty interface
func main() {
//map, key character string ,value Any type
map1 := make(map[string]interface{})
map1["name"] = " Zhang San "
map1["age"] = 18
map1["friend"] = []string{" Li Si ", " Wang Wu "}
fmt.Printf("map value :%v, map type :%T\n", map1, map1)
// section , Store any type
slice1 := []interface{}{1, " Zhang San ", true}
fmt.Printf(" Slice value :%v, Slice type :%T\n", slice1, slice1)
// Array , Store any type
array1 := [3]interface{}{2, " Li Si ", true}
fmt.Printf(" Array value :%v, An array type :%T\n", array1, array1)
}
Interface nesting ( Inherit )
Interfaces are multi inherited , A class can inherit multiple parent classes .

As shown in the figure , Interface C Inherited interface A(test1() Method ) And interface B(test2() Method ), Interface C Own test3() Method . So implement the interface C It needs to be implemented at the same time A\B\C Methods of three interfaces .
You can define a structure , Realization A\B\C Methods of three interfaces . Which interface implementation is this structure , Depends on the type of variable declaration .
// Interface A
type A interface {
test1()
}
// Interface B
type B interface {
test2()
}
// Interface C, Inherited interface A/B
type C interface {
A
B
test3()
}
// Structure
type Xtest struct {
}
// Method realization
func (x Xtest) test1() {
fmt.Println("test1() Method ...")
}
func (x Xtest) test2() {
fmt.Println("test2() Method ...")
}
func (x Xtest) test3() {
fmt.Println("test3() Method ...")
}
func main() {
var x1 Xtest = Xtest{}
fmt.Println("-- Interface A The implementation of the --") // Only test1 Method , Unable to call test2、test3 Method
var a1 A = x1
a1.test1()
fmt.Println("-- Interface B The implementation of the --") // Only test2 Method , Unable to call test1、test3 Method
var b1 B = x1
b1.test2()
fmt.Println("-- Interface C The implementation of the --") // You can call test1、test2、test3 Method
var c1 C = x1
c1.test1()
c1.test2()
c1.test3()
}Interface assertion
Get the real type accepted by the interface
Grammar 1 :
Determine whether the interface object is an actual type , Yes, the Boolean parameter is true, conversely false.
Variable parameters , Boolean parameters := Interface object .( Actual type )
Grammar II :
Realize polymorphic processing for different structures .
switch Variable parameters := Interface object .(type) {
case Actual type 1:
...
case Actual type 2:
...
}// Interface
type USB interface {
start()
stop()
}
// Mouse structure
type Mouse struct {
name string
}
// Flash memory structure
type FlashDisk struct {
name string
}
// Structure method
func (m Mouse) start() {
fmt.Println(m.name, " The mouse starts to work ...")
}
func (m Mouse) stop() {
fmt.Println(m.name, " The mouse stops working ...")
}
func (f FlashDisk) start() {
fmt.Println(f.name, " Flash memory inserted , You can start using ...")
}
func (f FlashDisk) stop() {
fmt.Println(f.name, " Flash memory unplugged ...")
}
// The test method
func testInterface(usb USB) {
switch instaceType := usb.(type) {
case Mouse:
fmt.Println(" You connected the mouse , Checking initialization driver ...")
instaceType.start()
instaceType.stop()
case FlashDisk:
fmt.Println(" You access storage , Scanning disk ...")
instaceType.start()
fmt.Println(" You can unplug the storage at any time ...")
instaceType.stop()
}
}
func main() {
mouse1 := Mouse{" Thunder snake super mouse "}
flashDisk1 := FlashDisk{"15TB Super flash "}
testInterface(mouse1)
fmt.Println("------------------")
testInterface(flashDisk1)
}

边栏推荐
- Review: effects of repetitive transcranial magnetic stimulation rTMS on resting state functional connectivity
- First Canary deployment with rancher
- Representation learning of resting fMRI data based on variational self encoder
- 原生JS路由,iframe框架
- GO语言-结构体
- [North Asia data recovery] SQLSERVER database encrypted data recovery case sharing
- AAAI 2022 | sasa: rethinking point cloud sampling in 3D object detection
- Bookstack: an open source wiki platform
- Operator Tour (I)
- Selection (042) - what is the output of the following code?
猜你喜欢

C multithreading

Someone is storing credit card data - how do they do it- Somebody is storing credit card data - how are they doing it?

Fundamentals of C language 13: file input / output

Idea restart

2022awe opened in March, and Hisense conference tablet was shortlisted for the review of EPLAN Award

Phantom star VR product details 32: Infinite War

First Canary deployment with rancher
![[Yugong series] February 2022 wechat applet -app Subpackages and preloadrule of JSON configuration attribute](/img/94/a2447b3b00ad0d8fb990917531316d.jpg)
[Yugong series] February 2022 wechat applet -app Subpackages and preloadrule of JSON configuration attribute

What is a good product for children's serious illness insurance? Please recommend it to a 3-year-old child

2022 Hunan latest fire facility operator simulation test question bank and answers
随机推荐
What is Objective-C ID in swift- What is the equivalent of an Objective-C id in Swift?
Three disciplines of elastic design, how to make the stability KPI high?
Non local network: early human attempts to tame transformer in CV | CVPR 2018
Factorial summation
A horse stopped a pawn
[Yugong series] February 2022 wechat applet -app Subpackages and preloadrule of JSON configuration attribute
启牛学堂app下载证券开户,是安全的吗?有风险嘛?
New project template of punctual atom F103 based on firmware library
GO语言-方法
C语言的指针
Kubernetes deployment language
Best practice | how to use Tencent cloud micro build to develop enterprise portal applications from 0 to 1
2022awe opened in March, and Hisense conference tablet was shortlisted for the review of EPLAN Award
Phantom star VR product details 32: Infinite War
MNIST model training (with code)
进程之间使用共享内存通信
【PyTorch基础教程29】DIN模型
我不太想在网上开户,网上股票开户安全吗
Select everything between matching brackets in vs Code - select everything between matching brackets in vs Code
模拟设计磁盘文件的链接存储结构