当前位置:网站首页>[golang] quick review guide quickreview (VII) -- Interface
[golang] quick review guide quickreview (VII) -- Interface
2022-06-23 20:04:00 【DDGarfield】
stay C# in , Interface is one of the ways to realize polymorphism , But interfaces focus more on the capabilities of objects , It's a norm . If you inherit the interface , You must implement the interface according to the requirements of the interface . There can be inheritance between interfaces . and golang The interface , Is a collection of methods ,duck-type programming A manifestation of .
If there is an animal that can walk like a duck , It sounds like a duck , So we think this is the duck .
1.C# The interface of
As mentioned above ,C# Our interface focuses on capabilities , Good interface function ( Ability ) A single , Interface can inherit interface , Class can inherit multiple interfaces ( Multiple abilities ), If you inherit the interface , It must all be realized .
1.1 Interface definition
Attributes can be defined in the interface , Indexer , Even events , Next we define an athlete IPlayer The interface of :
public interface IPlayer
{
// Interfaces can define properties
string Name { get; set; }
double Height { get; set; }
int Age { get; set; }
// motion
void PlaySport();
}
1.2 Interface inherits interface
Define a professional basketball player interface IBasketPlayer,
- First of all, professional basketball players are also athletes , So inherit the athlete interface
IPlayer - secondly , No matter which League it is, professional athletes , In addition to having some general technical capabilities , Will face a transfer event
TransferEvent
public interface IBasketPlayer: IPlayer
{
// Arm Exhibition
double Wingspan { get; }
// Vertical touch height
double Verticalreach { get; }
// Vertical jump
double Verticalleap { get; }
// Indexer To demonstrate , Force an indexer
string this[string index]
{
get; set;
}
event EventHandler TransferEvent;
// dunk
void Dunk();
// Pass the ball
void Pass();
void Dribble();
//3 Divide the ball
void ThreePointShot();
// Medium and long distance
void TwoPointShot();
// Air connection
void AlleyOop();
// rebounds
void Backboard();
}
1.3 Implementation interface
- Define a NBA players
NBAPlayer
public class NBAPlayer : IBasketPlayer
{
// Indexer
public string this[string index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Arm Exhibition
public double Wingspan => throw new NotImplementedException();
// Vertical touch height
public double Verticalreach => throw new NotImplementedException();
// Vertical takeoff
public double Verticalleap => throw new NotImplementedException();
// full name
public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// height
public double Height { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Age
public int Age { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public event EventHandler TransferEvent;
public void AlleyOop()
{
throw new NotImplementedException();
}
public void Backboard()
{
throw new NotImplementedException();
}
public void Dribble()
{
throw new NotImplementedException();
}
public void Dunk()
{
throw new NotImplementedException();
}
public void Pass()
{
throw new NotImplementedException();
}
public void PlaySport()
{
throw new NotImplementedException();
}
public void ThreePointShot()
{
throw new NotImplementedException();
}
public void TwoPointShot()
{
throw new NotImplementedException();
}
}
- Defining a CBA players Implementation interface
CBAPlayer:
public class CBAPlayer : IBasketPlayer
{
// Indexer
public string this[string index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Arm Exhibition
public double Wingspan => throw new NotImplementedException();
// The hammer touches high
public double Verticalreach => throw new NotImplementedException();
// Vertical takeoff
public double Verticalleap => throw new NotImplementedException();
// full name
public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// height
public double Height { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Age
public int Age { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Transfer events
public event EventHandler TransferEvent;
public void AlleyOop()
{
throw new NotImplementedException();
}
public void Backboard()
{
throw new NotImplementedException();
}
public void Dribbl()
{
throw new NotImplementedException();
}
public void Dunk()
{
throw new NotImplementedException();
}
public void Pass()
{
throw new NotImplementedException();
}
public void PlaySport()
{
throw new NotImplementedException();
}
public void ThreePointShot()
{
throw new NotImplementedException();
}
public void TwoPointShot()
{
throw new NotImplementedException();
}
}
1.4 Implement multiple interfaces
NBA Many black players , Not only can I play basketball , Can also rap ,( black , Everyone can dance , Can rap ,^_^), The famous one is Iverson , Artest , Lillard , Especially Iverson Allen Iverson, Many music platforms can find , however CBA Players don't have to rap , So continue to define a rap interface IRapper
public interface IRapper
{
void Rapper();
}
public class NBAPlayer : IBasketPlayer,IRapper
{
// Indexer
public string this[string index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Arm Exhibition
public double Wingspan => throw new NotImplementedException();
// The hammer touches high
public double Verticalreach => throw new NotImplementedException();
// Vertical takeoff
public double Verticalleap => throw new NotImplementedException();
// full name
public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// height
public double Height { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// Age
public int Age { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
// transfer
public event EventHandler TransferEvent;
// Can rap
public void Rapper()
{
throw new NotImplementedException();
}
public void AlleyOop()
{
throw new NotImplementedException();
}
public void Backboard()
{
throw new NotImplementedException();
}
public void Dribbl()
{
throw new NotImplementedException();
}
public void Dunk()
{
throw new NotImplementedException();
}
public void Pass()
{
throw new NotImplementedException();
}
public void PlaySport()
{
throw new NotImplementedException();
}
public void ThreePointShot()
{
throw new NotImplementedException();
}
public void TwoPointShot()
{
throw new NotImplementedException();
}
}
2.Golang The interface of
C# The interface of can be said to be a kind of specification , It can contain Specification of data , For example, properties , event , Indexer , It can also include Behavior ( Method ) The specification of , however Golang Somewhat different :Golang Don't care about data , Only care about behavior ( Method ).
2.1 Interface definition
An interface is a type , Abstract type , Like definition struct Same definition :
type Player interface {
PlaySport()
}
2.2 Implementation interface
An object ( Can be the receiver of the method ) As long as the methods defined in the interface are implemented , Even if you implement this interface .
func main(){
var player Player = &NBAPlayer{
Name: "James",
}
player.PlaySport()
}
type Player interface {
PlaySport()
}
type NBAPlayer struct {
Name string
Height float32
Age int8
Wingspan float32
Verticalreach float32
Verticalleap float32
}
// The pointer receiver implements the interface
func (p *NBAPlayer) PlaySport() {
fmt.Println(p.Name, " I am engaged in basketball ")
}
James I am engaged in basketball
ps: If the code above uses the value receiver
func (p NBAPlayer) PlaySport(), Both structure and structure pointer can be assigned to interface variables , because Go There is a syntax sugar for evaluating pointer type variables , The structure pointer is automatically evaluated internally*struct. If you use the pointer receiver as in the above code , Then the interface variable must pass a pointer . If you are not proficient in this problem , In the actual code, the compiler will beat you in the face again and again .
2.3 Implement multiple interfaces
One NBA Players have to achieve Player Interface , And realize Rapper Interface :
func main(){
var player Player = &NBAPlayer{
Name: "James",
}
var rapper Rapper = &NBAPlayer{
Name: "James",
}
player.PlaySport()
rapper.Rapper()
}
type Rapper interface {
Rapper()
}
type Player interface {
PlaySport()
}
type NBAPlayer struct {
Name string
Height float32
Age int8
Wingspan float32
Verticalreach float32
Verticalleap float32
}
// The pointer receiver implements the interface
func (p *NBAPlayer) PlaySport() {
fmt.Println(p.Name, " I am engaged in basketball ")
}
func (p *NBAPlayer) Rapper() {
fmt.Println(p.Name, " Can also rap ")
}
James I am engaged in basketball
James Can also rap
2.4 Nested Interfaces
Interface BasketPlayer Nested Interfaces Player,Rapper, This is similar to C# Interface can inherit interface .
func main(){
var nbaplayer BasketPlayer = &NBAPlayer{
Name: "Allen Iverson",
}
nbaer.PlaySport()
nbaer.Rapper()
nbaer.Dunk()
}
type BasketPlayer interface {
Player
Rapper
Dunk()
}
func (p *NBAPlayer) PlaySport() {
fmt.Println(p.Name, " I am engaged in basketball ")
}
func (p *NBAPlayer) Rapper() {
fmt.Println(p.Name, " Can also rap ")
}
func (p *NBAPlayer) Dunk() {
fmt.Println(p.Name, " Can dunk ")
}
Allen Iverson I am engaged in basketball
Allen Iverson Can also rap
Allen Iverson Can dunk
2.5* Empty interface
An empty interface is an interface that does not have any methods defined .** So any type implements an empty interface .** Apply the lines of Stephen Chow's films ,” In fact, there is no empty interface at all , Maybe everything is an empty interface “, Variables of empty interface type can store variables of any type .
2.5.1 Empty interface slice
- to glance at
fmtBagPrintlnMethod , A parameter is a slice of an empty interface
func Println(a ...interface{}) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
2.5.2 Save arbitrary values map
- We define map
make(map[TKey]TValue), WhenTValueSwitch tointerface{}Empty interface , By this timemapOfvalueIs no longer a single type , It can be of any type .
var player = make(map[string]interface{})
player["name"] = "LeBron James"
player["age"] = 36
2.5.3 Types of assertions
Type assertions are mainly used to determine values in empty interfaces , Because the null connection represents any type .x.(T)
var x interface{}
x = "randyfield"
v, ok := x.(string)
if ok {
fmt.Println(v)
} else {
fmt.Println(" Assertion failed ")
}
About interfaces , Don't write interfaces for interfaces , Will add unnecessary abstraction , Causes unnecessary runtime wear and tear .
边栏推荐
- 国内期货开户怎么开?哪家期货公司开户更安全?
- 【Golang】快速复习指南QuickReview(八)——goroutine
- 「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能
- LeetCode 260. 只出现一次的数字 III
- Stochastic process -- Markov chain
- SAP实施项目上的内部顾问与外部顾问,相互为难还是相互成就?
- Are there conditions for making new bonds? Is it safe to make new bonds
- 测试的重要性及目的
- Elastricearch's fragmentation principle of the second bullet
- Ready to migrate to the cloud? Please accept this list of migration steps
猜你喜欢

小程序开发框架推荐

LeetCode 260. Number III that appears only once

金九银十,靠这个细节,offer拿到手软!

Activity registration | introduction to mongodb 5.0 sequential storage features

UST 崩盘后,稳定币市场格局将迎来新机遇?

How to write a great online user manual in 7 steps

Hardware development notes (6): basic process of hardware development, making a USB to RS232 module (5): creating USB package library and associating principle graphic devices

SQL联合查询(内联、左联、右联、全联)的语法

火线沙龙第26期-多云安全专场

技术分享| WVP+ZLMediaKit实现摄像头GB28181推流播放
随机推荐
Syntax of SQL union query (inline, left, right, and full)
金鱼哥RHCA回忆录:DO447管理用户和团队的访问--用团队有效地管理用户
Use of the vs2022scanf function. An error is reported when using scanf - the return value is ignored: Solutions
Stochastic process -- Markov chain
【Golang】类型转换归纳总结
Are internal consultants and external consultants in SAP implementation projects difficult or successful?
混沌工程,了解一下
@@脚本实现Ishell自动部署
The "open source star picking program" container pulls private images from harbor, which is a necessary skill for cloud native advanced technology
Logstash start -r parameter
MySQL时间函数的运用,简单问题
JS高级程序设计第 4 版:生成器的学习
Kinsoku jikou desu新浪股票接口变动
官宣.NET 7 预览版5
Crise de 35 ans? Le volume intérieur est devenu synonyme de programmeur...
Goldfish rhca memoirs: do447 managing user and team access -- effectively managing users with teams
RStudio 1.4软件安装包和安装教程
如何在Microsoft Exchange 2010中安装SSL证书
八大误区,逐个击破(终篇):云难以扩展、定制性差,还会让管理员失去控制权?
Rendering of kotlin jetpack compose tab using animatedvisibility