当前位置:网站首页>[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 fmt Bag Println Method , 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), When TValue Switch to interface{} Empty interface , By this time map Of value Is 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 .

原网站

版权声明
本文为[DDGarfield]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231941491651.html