当前位置:网站首页>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 .
}

边栏推荐
- Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
- Homology policy / cross domain and cross domain solutions /web security attacks CSRF and XSS
- 技术干货|百行代码写BERT,昇思MindSpore能力大赏
- 你开发数据API最快多长时间?我1分钟就足够了
- 【MySQL 12】MySQL 8.0.18 重新初始化
- [mindspire paper presentation] summary of training skills in AAAI long tail problem
- The underlying mechanism of advertising on websites
- VMWare网络模式-桥接,Host-Only,NAT网络
- Vertx restful style web router
- docket
猜你喜欢

带你全流程,全方位的了解属于测试的软件事故

最全SQL与NoSQL优缺点对比

技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验

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

不出网上线CS的各种姿势
![PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef](/img/65/1f28071fc15e76abb37f1b128e1d90.jpg)
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef

【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题

PAT甲级 1032 Sharing

URL programming

技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型
随机推荐
截图工具Snipaste
Dora (discover offer request recognition) process of obtaining IP address
专题 | 同步 异步
The concept of C language pointer
【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
HISAT2 - StringTie - DESeq2 pipeline 进行bulk RNA-seq
图像识别与检测--笔记
URL programming
Technology dry goods | luxe model for the migration of mindspore NLP model -- reading comprehension task
Industrial resilience
Mail sending of vertx
The babbage industrial policy forum
Lucene introduces NFA
An overview of IfM Engage
Hello world of vertx
c语言指针的概念
Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake
Reconnaissance et détection d'images - Notes
技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
Project experience sharing: realize an IR Fusion optimization pass of Shengsi mindspire layer