code explame

An example of interface code is shown below. So how do you think about an interface? Officially, an interface is a set of method signatures, and whoever implements all of the methods in that set of signatures implements that interface. The code & use case diagram is shown below

package main

import "fmt"

type People interface {
	name(name string)
	age(age int)}type Student struct {
	score uint
}

type Teacher struct{}func (s *Student) name(nm string) {
	fmt.Println("Student name is %s ", nm)
}

func (s *Student) age(age int) {
	fmt.Println("Student age is ", age)
}

func (t *Teacher) name(nm string) {
	fmt.Println("Teacher name is ", nm)
}

func (t *Teacher) age(age int) {
	fmt.Println("Teacher age is ", age)
}

// Define the interface variable
var conn People

func GetStudentConn(a) People {
	conn = &Student{score: 100}
	return conn
}

func GetTeacherConn(a) People {
	conn = &Teacher{}
	return conn
}

func main(a) {
	stuConn := GetStudentConn()
	stuConn.age(100)

	teaConn := GetTeacherConn()
	teaConn.name("tea")}Copy the code

In my opinion, go interface is a bit like the concept of abstract class in CPP, which means that the abstract class only defines the signature of pure virtual functions, and its subclasses implement the signature of these functions concretely. It is also said that the interface of GO is like CPP polymorphism. CPP polymorphism refers to the base class pointer pointing to the object of the subclass, so that the virtual function pointer points to the object of the subclass and the virtual table is called. I think it is not like that. Welcome to discuss)

class Shape 
{
public:
   // Provides pure virtual functions for the interface framework
   virtual int getArea(a) = 0;
   void setWidth(int w)
   {
      width = w;
   }
   void setHeight(int h)
   {
      height = h;
   }
protected:
   int width;
   int height;
};
 
/ / a derived class
class Rectangle: public Shape
{
public:
   int getArea(a)
   { 
      return(width * height); }};class Triangle: public Shape
{
public:
   int getArea(a)
   { 
      return (width * height)/2; }};int main(void)
{
   Rectangle Rect;
   Triangle  Tri;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
   // Output the area of the object
   cout << "Total Rectangle area: " << Rect.getArea() << endl;
 
   Tri.setWidth(5);
   Tri.setHeight(7);
   // Output the area of the object
   cout << "Total Triangle area: " << Tri.getArea() << endl; 
 
   return 0;
}
Copy the code