当前位置:网站首页>Go interface Foundation
Go interface Foundation
2022-07-28 08:54:00 【go|Python】
List of articles
go Interface Basics
In the field of object-oriented , Interfaces are generally defined like this : Interface defines the behavior of an object . The interface only specifies what the object should do , As for how to achieve this behavior ( That's the implementation details ), It's up to the object itself .
stay Go In language , An interface is a method signature (Method Signature) Set . When a type defines all the methods in the interface , We say it implements the interface . This is similar to object-oriented programming (OOP) It's very similar . Interface specifies the method that a type should have , And it's up to the type to decide how to implement these methods .
With python Take the duck type as an example : If there is a duck's way of walking in the class , The way ducks talk , No matter what kind you are , You are all duck type .
class Duck: # Define duck type
def speak(self):
pass
def run(self):
pass
class Cat: # Although there is no inheritance Duck class , however Cat Namely Duck This type
def speak(self):
pass
def run(self):
pass
Popular point theory : There is no need for explicit inheritance , As long as you have Duck Methods in class , You are the one Duck Subclasses of classes
stay go In language , There is also the concept of duck type , We call it an interface (interface)
Definition of interface
- An interface is actually a type
// Defining interfaces An interface is a collection of methods But it didn't work The object needs to implement itself
type Duck interface {
speak(s string)
run()
}
Implementation and use of interface
func main() {
tduck := TDuck{
" Donald Duck 1 Number ", 4}
tduck.speak(" The most stupid ") // Donald said : My name is Donald Duck 1 Number I am a The most stupid
tduck.run() // Donald Duck 1 Number Walk awkwardly
}
// Defining structure
type TDuck struct {
name string
age int
}
type PDuck struct {
name string
age int
}
// Donald Duck , Realization speak and run
func (t TDuck) speak(s string) {
fmt.Println(" Donald said : My name is ", t.name, " I am a ", s)
}
func (t TDuck) run() {
fmt.Println(t.name," Walk awkwardly ")
}
// Ordinary duck , Realization speak and run
func (t PDuck)speak(s string) {
fmt.Println(" I am an ordinary duck , My name is :",t.name," I said, :",s)
}
func (t PDuck)run() {
fmt.Println(" I am an ordinary duck , My name is :",t.name," I walk askew ")
}

It should be noted that , stay go Implementation of interface in , All methods in the interface must be implemented , Only then can the logo in the above figure appear , Even if only one method is not implemented , It is not an implementation interface .
The practical use of the interface
TDuck Realized Duck Interface , therefore TDuck All of them are Duck Object of type , I can assign a value to Duck Object of type , But you can only use methods in the interface , You cannot use specific types of attributes .
func main() {
tduck := TDuck{
" Donald Duck 1 Number ", 4}
tduck.speak(" The most stupid ") // Donald said : My name is Donald Duck 1 Number I am a The most stupid
tduck.run() // Donald Duck 1 Number Walk awkwardly
test5(tduck," The most stupid ") // The ginseng
var duck Duck
duck = tduck // Direct assignment
}
func test5(d Duck, s string) {
d.run() // Donald said : My name is Donald Duck 1 Number I am a The fiercest
d.speak(s) // Donald Duck 1 Number Walk awkwardly
}
Empty interface and anonymous empty interface
An interface that does not contain a method is called an empty interface . An empty interface is represented as interface{}. Because there is no method for an empty interface , So all types implement empty interfaces .
type Panada interface {
}
func PrintPa(i Panada) {
fmt.Printf("Type = %T, value = %v\n", i, i)
}
func main() {
PrintPa(10) // Type = int, value = 10
PrintPa("lxx") // Type = string, value = lxx
PrintPa([3]int{
1,2,3}) // Type = [3]int, value = [1 2 3]
}
Anonymous empty interface , It's simply an empty interface without a name , Use only once , It is written as follows
func PrintPa(i interface {
}) {
fmt.Printf("Type = %T, value = %v\n", i, i)
}
Types of assertions
Type assertions are used to extract the underlying values of the interface , In grammar i.(T) in , Interface i The specific type of the new model is T, This syntax is used to get the underlying value of the interface . Used to solve in function , Use when you need to use the properties of the structure object that implements this interface . The code is as follows
func main() {
tduck := TDuck{
" Donald Duck 1 Number ", 4}
test5(tduck," The most stupid ")
}
func test5(d Duck, s string) {
d.run()
d.speak(s)
// Interface objects have only methods , There is no specific type (tduck) Properties of
//fmt.Println(d.name) // Report errors
v,ok := d.(TDuck)
// ok by true when , Assert success , by false Assertion failed
// You can also use v := d.(TDuck) How to write it , But this way of writing will throw exceptions once the assertion fails , Not recommended
if ok {
fmt.Println(v.name) // Donald Duck 1 Number
fmt.Println(v.age) // 4
}
}
Type selection
Type selection is used to associate specific types of interfaces with many case Statement . It's with the general switch Statements like . The only difference is that type selection specifies the type , And general switch The specified value is .
The syntax of type selection is similar to type assertion . The syntax of type assertion is i.(T), And for type selection , type T By keyword type Instead of .
func main() {
tduck := TDuck{
" Donald Duck 1 Number ", 4}
pduck := PDuck{
" Old duck 1 Number ", 4}
test6(tduck, " The most stupid ")
test6(pduck, " The most ignorant ")
}
func test6(d Duck, s string) {
switch obj := d.(type) {
case TDuck:
obj.run()
fmt.Println(obj.name)
case PDuck:
obj.speak(s)
fmt.Println(obj.age)
}
}
Add :
- The zero value of the interface is nil So the interface is a reference type
- The underlying implementation of the interface points to a specific type through a pointer (type : value)
typeIt's the specific type of the underlying interface (Concrete Type), andvalueIs the value of a specific type .
var duck Duck
fmt.Println(duck) // <nil>
边栏推荐
- 49 opencv deep analysis profile
- 看完这12个面试问题,新媒体运营岗位就是你的了
- Quickly build a gateway service, dynamic routing and authentication process, and watch the second meeting (including the flow chart)
- I use SqlClient normally, and dlink submission will report this error. What should I do?
- 模型预测控制(MPC)解析(九):二次规划的数值解(下)
- Why can ThreadLocal achieve thread isolation?
- HCIP---LDP和MPLS技术(详解)
- Ciou loss
- 1w5字详细介绍分布式系统的那些技术方案
- How does QT delete all controls in a layout?
猜你喜欢

NDK series (6): let's talk about the way and time to register JNI functions

Can‘t connect to server on ‘IP‘ (60)

XMIND Zen installation tutorial

C轮融资已完成!思迈特软件领跑国内BI生态赋能,产品、服务竿头一步

Do you know the five minute rule and the ten byte rule?

Gbase 8A MPP and Galaxy Kirin (x86 version) complete deep adaptation

思迈特软件Smartbi完成C轮融资,推动国产BI加速进入智能化时代

客户至上 | 国产BI领跑者,思迈特软件完成C轮融资

1w5 words to introduce those technical solutions of distributed system in detail

Smartbi of smart smart smart software completed the c-round financing and accelerated the domestic Bi into the intelligent era
随机推荐
NDK series (6): let's talk about the way and time to register JNI functions
Competition: diabetes genetic risk detection challenge (iFLYTEK)
PHP基础知识 - PHP 使用 PDO
Uniapp ---- detailed steps to obtain the longitude and latitude of the current position and other information (including applet)
Recycling of classes loaded by classloader
Bash shell interaction free
Do you know the five minute rule and the ten byte rule?
Redis 基本知识,快来回顾一下
When will brain like intelligence, which is popular in academia, land? Let's listen to what the industry masters say - qubits, colliders, x-knowledge Technology
Why can ThreadLocal achieve thread isolation?
第2章-14 求整数段和
Introduction to self drive tour of snow mountains in the West in January 2018
kubernetes之Deployment
Machine learning how to achieve epidemic visualization -- epidemic data analysis and prediction practice
微服务架构 Sentinel 的服务限流及熔断
Vrrp+mstp configuration details [Huawei ENSP experiment]
This flick SQL timestamp_ Can ltz be used in create DDL
第2章-2 计算分段函数[1]
View the dimensions of the list
Smart software completed round C financing, making Bi truly "inclusive"