当前位置:网站首页>Go language foundation ----- 07 ----- method
Go language foundation ----- 07 ----- method
2022-07-03 07:37:00 【Mango sauce】
1 Introduction of methods
- 1) Concept of method : Simply put, it is a function in an object , Called method .
- 2) stay go In language , You can give any custom type ( Includes built-in types , But excluding pointer types ) Add the corresponding method .
- 3) Methods always bind object instances , And implicitly take the instance as the first parameter .
- 4) The grammar of the method :
func (receiver receiverType) funcName(parameters) (results)
// 1. receiver For any name .
// 2. receiverType Is the type of caller . It can be T perhaps *T. Be careful T Itself cannot be an interface or pointer .
for example T=int, But it can't be *int. You can do this if you want the pointer :T=int after , Add one separately *.
// Code interpretation :
// 1. Write it correctly
type myint int
func (s *myint) Add() (r int)
// 2. Wrong writing . because T The type itself cannot be a pointer .
type myintp *int
func (s myintp) Add() (r int)
- 5) Method does not support overloading , That is, it does not support , Methods with the same function name and different formal parameters . Be careful , In different types , Can have the same function name . The following example will explain .
2 The difference between procedure oriented and object-oriented functions
It's simple , Is to encapsulate the function into an object , Then pass the variable name + Call in the form of points . Use the following example .
package main
import "fmt"
// go There is no such thing as long type
type long int
func Add01(a, b long)long{
return a + b
}
func (t long)Add02(b long)long{
return t + b
}
func main(){
// 1. Process oriented
fmt.Println("Add01 = ", Add01(1, 2))
// 2. object-oriented
var s1 long = 1
fmt.Println("Add02 = ", s1.Add02(5))
}
3 Structure type adding method
package main
import "fmt"
type Persion struct {
name string
sex byte
age int
}
// Functions with receivers are called methods
func (t Persion) PrintInfo(){
fmt.Println("PrintInfo = ", t)
}
func (t *Persion) SetInfo(n string, s byte, a int){
t.name = n
t.sex = s
t.age = a
}
func main(){
// 1. Ordinary variables are passed as implicit instances
p := Persion{
"hc", 'w', 24}
p.PrintInfo()
// 2. Pointer variables are passed as implicit instances
(&p).SetInfo("lqq", 'w', 24)
p.PrintInfo()
}
4 Method related precautions
- 1) The receiver itself cannot be a pointer type , The top will be 1 It was also emphasized at point .
// 1. Correct writing
type long int
func (t long)test(){
}
// 2. The wrong way to write
// err:Invalid receiver type 'pointer' ('pointer' is a pointer type)
type pointer *int
func (t pointer)test(){
}
- 2)go Method of does not support overloading . For example, writing grammar like this will report errors . Because the type of receiver is the same , And the name is the same .
type long int
func (t long)test(){
}
type long int
func (t long)test(a int){
}
And the following is not wrong , Because the receiver type is different . It can be used C++ Two classes are defined , Class has the same member function name to understand .
type long int
func (t long)test(){
}
type char byte
func (c char) test(a int){
}
5 Receiver's value semantics and reference semantics
- 1) Ordinary variables as receivers are value passing .
- 2) Pointer variables are passed by reference as recipients .
Look back at the code above 3 Dot Structure type adding method .
6 Method set of pointer type and variable type
Method sets are actually how methods can be called using pointers , And how ordinary variables call methods . When a variable calls its own method set , It is not constrained by whether the variable itself is a pointer or an ordinary variable , You can use “ Variable name + spot (.) + Method name ” Form call of .
for example :
package main
import "fmt"
type Persion struct {
name string
sex byte
age int
}
// Functions with receivers are called methods
func (t Persion) SetInfoValue(){
fmt.Println("SetInfoValue")
}
func (t *Persion) SetInfoPointer(){
fmt.Println("SetInfoPointer")
}
func main(){
// 1. When the structure variable is a pointer , Which methods can it call , Is a method set
// How pointers call methods
p := &Persion{
"hc", 'w', 24}
p.SetInfoPointer()
p.SetInfoValue() // It will automatically convert internally , Put the pointer p Turn into (*p).SetInfoValue(), So the following calling methods are also possible , So when calling a method, you don't need to consider whether it is a pointer or a variable
(*p).SetInfoValue()
fmt.Println("===========")
// 2. How ordinary variables call methods
p2 := Persion{
"lqq", 'w', 24}
p2.SetInfoValue()
p2.SetInfoPointer() // Internal conversion to (&p2).SetInfoPointer(), So the following calling methods are also possible
(&p2).SetInfoPointer()
}

7 Method inheritance
package main
import "fmt"
type Persion struct {
name string
sex byte
age int
}
// Persion Implemented a method
func (t *Persion) PrintInfo(){
fmt.Printf("name=%s, byte=%c, age=%d\n", t.name, t.sex, t.age)
}
// Another structure inherits this Persion, It will inherit all members and their methods
type Student struct {
Persion // Anonymous field
id int
addr string
}
func main(){
s := Student{
Persion{
"hc", 'w', 24}, 1, "sz"}
s.PrintInfo()
}
8 Method rewrite
go Override of method in , It's actually C++ The polymorphism of ( Through the virtual base class pointer 、virtual Keyword implementation ).
Below go Examples of implementing polymorphism .
package main
import "fmt"
type Persion struct {
name string
sex byte
age int
}
// Persion Implemented a method
func (t *Persion) PrintInfo(){
fmt.Printf("name=%s, byte=%c, age=%d\n", t.name, t.sex, t.age)
}
// Another structure inherits this Persion, It will inherit all members and their methods
type Student struct {
Persion // Anonymous field
id int
addr string
}
// Student Also add a method with the same name PrintInfo
// Be careful , Because the receiver type is *Persion、 One is *Student, They are different , So the function name can be the same .
// This is also called method rewriting , That is, polymorphism .
func (t *Student) PrintInfo(){
fmt.Println("stu = ", t)
}
func main(){
s := Student{
Persion{
"hc", 'w', 24}, 1, "sz"}
// According to the principle of proximity , It's called Student.PrintInfo()
s.PrintInfo()
// The display call can only be called to Persion Of PrintInfo()
s.Persion.PrintInfo()
}

9 Method value and method expression
- 1) The method is worth : Implicit call , Call by implicitly saving the receiver .
- 2) Method expression : Display call , Recipients are not implicitly saved , When calling, you need to display the type of instance transferred to the corresponding receiver .
Code example :
package main
import "fmt"
type Persion struct {
name string
sex byte
age int
}
// Functions with receivers are called methods
func (t Persion) SetInfoValue(){
fmt.Println("SetInfoValue")
}
func (t *Persion) SetInfoPointer(){
fmt.Println("SetInfoPointer")
}
func main(){
// 1. Method value call
p := &Persion{
"hc", 'w', 24}
pFunc := p.SetInfoPointer // The receiver is implicitly saved
pFunc()
vFunc := p.SetInfoValue
vFunc()
fmt.Println("==============")
// 2. Method expression call
p2 := Persion{
"lqq", 'w', 24}
f := (*Persion).SetInfoPointer // Recipients are not implicitly saved , So when calling, you need to send the corresponding instance to the receiver .(*Persion) It means that when passing an instance, it is an address rather than an ordinary variable .
f(&p2) // You need to send an instance to the receiver type .
f2 := (Persion).SetInfoValue // Persion It means that the instance is passed as a common variable instead of an address .
f2(p2) // You need to send an instance to the receiver type .
}

边栏推荐
- 【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
- VMware network mode - bridge, host only, NAT network
- PAT甲级 1032 Sharing
- Summary of Arduino serial functions related to print read
- TreeMap
- 技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型
- 技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
- FileInputStream and fileoutputstream
- PAT甲级 1031 Hello World for U
- 2021-07-18
猜你喜欢

Inverted chain disk storage in Lucene (pfordelta)

Why is data service the direction of the next generation data center?

Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing

技术干货|利用昇思MindSpore复现ICCV2021 Best Paper Swin Transformer

Lucene skip table

技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!

Take you through the whole process and comprehensively understand the software accidents that belong to testing

Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition

Es writing fragment process

Spa single page application
随机推荐
Le Seigneur des anneaux: l'anneau du pouvoir
pgAdmin 4 v6.11 发布,PostgreSQL 开源图形化管理工具
UA camouflage, get and post in requests carry parameters to obtain JSON format content
c语言指针的概念
Vertx metric Prometheus monitoring indicators
Epoll related references
论文学习——鄱阳湖星子站水位时间序列相似度研究
技术干货|昇思MindSpore NLP模型迁移之LUKE模型——阅读理解任务
Vertx restful style web router
最全SQL与NoSQL优缺点对比
【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
Leetcode 198: 打家劫舍
圖像識別與檢測--筆記
【CoppeliaSim4.3】C#调用 remoteApi控制场景中UR5
Traversal in Lucene
截图工具Snipaste
TreeMap
Unified handling and interception of exception exceptions of vertx
Docker builds MySQL: the specified path of version 5.7 cannot be mounted.