当前位置:网站首页>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 .
}
边栏推荐
- Vertx restful style web router
- Analysis of the problems of the 12th Blue Bridge Cup single chip microcomputer provincial competition
- lucene scorer
- PgSQL converts string to double type (to_number())
- Vertx metric Prometheus monitoring indicators
- Analysis of the problems of the 7th Blue Bridge Cup single chip microcomputer provincial competition
- Arduino Serial系列函数 有关print read 的总结
- Homology policy / cross domain and cross domain solutions /web security attacks CSRF and XSS
- Vertx's responsive MySQL template
- Beginners use Minio
猜你喜欢
Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
How long is the fastest time you can develop data API? One minute is enough for me
Spa single page application
Traversal in Lucene
技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
JS monitors empty objects and empty references
技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
URL programming
随机推荐
Epoll related references
Inverted chain disk storage in Lucene (pfordelta)
C WinForm framework
PAT甲级 1030 Travel Plan
Spa single page application
Map interface and method
技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估
URL programming
Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
Use of file class
论文学习——鄱阳湖星子站水位时间序列相似度研究
Traversal in Lucene
Arduino Serial系列函数 有关print read 的总结
[set theory] order relation (partial order relation | partial order set | example of partial order set)
Lucene hnsw merge optimization
The embodiment of generics in inheritance and wildcards
2021-07-18
Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
Technical dry goods Shengsi mindspire elementary course online: from basic concepts to practical operation, 1 hour to start!