当前位置:网站首页>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>
边栏推荐
- MySQL how to add users and set permissions?
- Shell编程规范与变量
- Detailed explanation of DHCP distribution address of routing / layer 3 switch [Huawei ENSP]
- I am a 27 year old technical manager, whose income is too high, and my heart is in a panic
- Alibaba technology has four sides + intersection +hr, and successfully got the offer. Can't double non undergraduate students enter the big factory?
- [soft test software evaluator] 2013 comprehensive knowledge over the years
- Gbase appears in Unicom cloud Tour (Sichuan Station) to professionally empower cloud ecology
- 5张图告诉你:同样是职场人,差距怎么这么大?
- The cooperation between starfish OS and metabell is just the beginning
- Vrrp+mstp configuration details [Huawei ENSP experiment]
猜你喜欢

When unity switches to another scene, he finds that the scene is dimmed

Uniapp ---- detailed steps to obtain the longitude and latitude of the current position and other information (including applet)

Win the bid! Nantah general gbase 8s won the bid for the 2022 database framework project of NARI Group

我来教你如何组装一个注册中心?

Chapter 2-14 sum integer segments
![[soft test software evaluator] 2013 comprehensive knowledge over the years](/img/c5/183acabd7015a5e515b7d83c127b2c.jpg)
[soft test software evaluator] 2013 comprehensive knowledge over the years

1w5字详细介绍分布式系统的那些技术方案

C #, introductory tutorial -- debugging skills and logical error probe technology and source code when the program is running

JS inheritance method

Competition: diabetes genetic risk detection challenge (iFLYTEK)
随机推荐
1w5 words to introduce those technical solutions of distributed system in detail
Argocd Web UI loading is slow? A trick to teach you to solve
SQL注入 ----前置基础
Day112. Shangyitong: Mobile verification code login function
GB/T 41479-2022信息安全技术 网络数据处理安全要求 导图概览
After reading these 12 interview questions, the new media operation post is yours
Leetcode brushes questions. I recommend this video of the sister Xueba at station B
GBASE亮相联通云巡展(四川站) 以专业赋能云生态
Pyspark changes the column order and saves it into iceberg database
第2章-14 求整数段和
Let me teach you how to assemble a registration center?
Kubernetes technology and Architecture (VII)
PHP基础知识 - PHP 使用 PDO
Introduction to self drive tour of snow mountains in the West in January 2018
2018年1月西邻雪山自驾游攻略
HCIP第九天_BGP实验
为什么 ThreadLocal 可以做到线程隔离?
Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始
Basic syntax of jquey
When unity switches to another scene, he finds that the scene is dimmed