[golang object oriented programming]

Posted by Drachlen on Sun, 27 Feb 2022 06:11:16 +0100

1, Three characteristics of object-oriented programming - encapsulation

1) Introduction

2) Quick start cases

package model
type person struct{
	Name string 
	age int
	salary float64
}
//Equivalent to constructor
func NewStudent(name string)*person{
	return &person{
		Name:name,
	}
func (p *person)SetAge(age int){
	if age>0&&age<150{
		p.age=age
	}else{
		fmt.Println("Wrong age range!!!")
	}
func (p *person)GetAge()int{
	return p.age
}
func (p *person)SetSal(sal float64){
	if sal>=3000&&sal<=30000{
		p.sal =sal
	}else{
		fmt.Println("Wrong salary range!!!")
	}
func (p *person)GetSal()float64{
	return p.salary
}
}
}
package main
import(
	"fmt"
	"go_code/project00/model"
)
func main(){
	var stu=model.NewStudent("tom",88.8)
	fmt.Println(*stu)
	fmt.Println("name=",stu.Name,"score=",stu.GetScore())
}

package model02
import(
	"fmt"
)
type account struct{
	accountNo string
	pwd string 
	balance float64
}
func NewAccount(No string,pwd string,balance float64)*account{
	if len(accountNo)<6||len(accountNo)>10{
		fmt.Println("Wrong account length...")
		return nil
	}
	if len(pwd)!=6{
		fmt.Println("The length of the password is incorrect...")
	}
	if balance<20{
		fmt.Println("Wrong balance...")
	}
	return &account{
		accountNo:No,
		pwd:pwd,
		balance:balance,
	}
	func (account *account) Deposite(money float64,pws string){
		if pwd != account.pwd {
			fmt.Println("The password you entered is incorrect")
			return
			}
			//See if the deposit amount is correct
			if money <= 0 {
			fmt.Println("The amount you entered is incorrect")
			return
			}
			account.balance += money
			fmt.Println("Deposit successful~~")
	}
	func (account *account) WithDraw(money float64, pwd string){
		if pwd != account.pwd {
			fmt.Println("The password you entered is incorrect")
			return
			}
			if money <= 0 || money > account.balance {
				fmt.Println("The amount you entered is incorrect")
				return
				}
				account.balance -= money
				fmt.Println("Withdrawal succeeded~~")	
	}
	func (account *account) Query(pwd string) {
		//Check whether the password entered is correct
		if pwd != account.pwd {
		fmt.Println("The password you entered is incorrect")
		return
		}
		fmt.Printf("Your account number is=%v balance=%v \n", account.accountNo, account.balance)
		}
	}

2, Three characteristics of object-oriented programming - inheritance

1) Grammar

2) Quick start

package main
import(
	"fmt"
)
type Student struct{
	Name string
	Age int
	Score int
}
func (stu *Student)ShowInfo(){
	fmt.Printf("full name:%v Age:%v Achievements:%v\n",stu.Name,stu.Age,stu.Score)

}
func (stu *Student)SetScore(score int){
	stu.Score=score
}
type pupil struct{
	Student
	
}
func (p *pupil)testing(){
	fmt.Println("Pupils are taking exams...")
}
type Graduate struct{
	Student
}
func (g *Graduate)testing(){
	fmt.Println("College students are taking exams...")
}
func main(){
	p:=pupil{}
	p.Name="tom"
	p.Age=18
	p.testing()
	p.SetScore(70)
	p.ShowInfo()

	g:=Graduate{}
	g.Name="tom"
	g.Age=18
	g.testing()
	g.SetScore(70)
	g.ShowInfo()
}

3) Details

  • Structures can use all fields and methods of nested anonymous structures
  • Anonymous structure field access can be simplified
  • The structure is embedded in two (or more) anonymous structures. If two anonymous structures have the same fields and methods (and the structure itself has no fields and methods with the same name), the name of the anonymous structure must be clearly specified during access
  • If a struct is nested with a well-known structure, this pattern is a combination. If it is a combination relationship, the name of the structure must be brought when accessing the fields or methods of the combined structure
  • After nesting anonymous structures, you can also directly specify the value of each anonymous structure field when creating a structure variable (instance)

3, Interface

1) Why is there an interface

2) Quick start

package main
import(
	"fmt"
)
import()
type Usb interface{
	Start()
	Stop()
}
type Phone struct{

}
func (p Phone)Start(){
	fmt.Println("Mobile start")
}
func (p Phone)Stop(){
	fmt.Println("End of mobile phone")
}
type Camera struct{}
func (c Camera)Start(){
	fmt.Println("Camera start")
}
func (c Camera)Stop(){
	fmt.Println("Camera end")
}
type Computer struct{}
func (c Computer)Working(usb Usb){
	usb.Start()
	usb.Stop()
}
func main(){
	computer:=Computer{}
	phone:=Phone{}
	camera:=Camera{}
	computer.Working(phone)
	computer.Working(camera)
}

3) Basic grammar

  • Contains no variables
  • The method in the interface has no method body
  • No explicit implementation is required

4) Pay attention to details

  • . the interface itself cannot create an instance, but it can point to a variable of a user-defined type that implements the interface
	var a Usb=phone
	a.Start()
	a.Stop()
  • As long as it is a user-defined data type, you can implement the interface, not just the structure type
  • The interface type is a = pointer (reference type) by default. If it is used without interface initialization, nil will be output
  • The empty interface {} has no method, so all types implement the empty interface, that is, we can assign any variable to the empty interface

4) Implementation interface vs inheritance
Interface is a supplement to inheritance

4, Three characteristics of object-oriented programming polymorphism

type Usb interface{
	Start()
	Stop()
}
type Phone struct{
	name string
}
func (p Phone)Start(){
	fmt.Println("Phone start")
}
func(p Phone)Stop(){
	fmt.Println("End of call")
}
func (p Phone)Call(){
	fmt.Println("The cell phone is on the phone")
}
type Camera struct{
	name string
}
func (c Camera)Start(){
	fmt.Println("Camera start")
}
func (c Camera)Stop(){
	fmt.Println("Camera end")
}
type Computer struct{}
func (c Computer)Working(usb Usb){
	usb.Start()
	usb.Stop()
}
func main(){
	var usbArr [3]Usb
	usbArr[0]=Phone{"vivo"}
	usbArr[1]=Phone{"millet"}
	usbArr[2]=Camera{"Sony"}
	var computer Computer

5, Type assertion

1) Demand
Assign an interface variable to a variable of user-defined type
2) Basic introduction
3) Best Practices 1

package main
import "fmt"
type Usb interface{
	Start()
	Stop()
}
type Phone struct{
	name string
}
func (p Phone)Start(){
	fmt.Println("Phone start")
}
func(p Phone)Stop(){
	fmt.Println("End of call")
}
func (p Phone)Call(){
	fmt.Println("The cell phone is on the phone")
}
type Camera struct{
	name string
}
func (c Camera)Start(){
	fmt.Println("Camera start")
}
func (c Camera)Stop(){
	fmt.Println("Camera end")
}
type Computer struct{}
func (c Computer)Working(usb Usb){
	usb.Start()
	phone,ok:=usb.(Phone);
	if ok{
		phone.Call()
	}
	usb.Stop()
}
func main(){
	var usbArr [3]Usb
	usbArr[0]=Phone{"vivo"}
	usbArr[1]=Phone{"millet"}
	usbArr[2]=Camera{"Sony"}
	var computer Computer
	for _,v :=range usbArr{
		computer.Working(v)
		fmt.Println()
	}
}


4) Best practices 2

func TypeJudge(item... interface{}){
	for i,v:=range item{
		switch v.(type){
		case bool:
			fmt.Printf("%v The first parameter is bool type,Value is%v\n",i,v)
		case int:
			fmt.Printf("%v The first parameter is int type,Value is%v\n",i,v)
		}
	

	}
}
func main(){
	var n1=true
	var n2 int =23
	TypeJudge(n1,n2)
}

summary

This article only briefly introduces the object-oriented programming of Golang. This article is a note made through the learning of Golang video in Silicon Valley at station b.

Topics: Go Back-end