当前位置:网站首页>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 11】怎么解决MySQL 8.0.18 大小写敏感问题
- Leetcode 198: 打家劫舍
- Hello world of vertx
- URL programming
- Docker builds MySQL: the specified path of version 5.7 cannot be mounted.
- Circuit, packet and message exchange
- Collector in ES (percentile / base)
- Jeecg menu path display problem
- An overview of IfM Engage
- Why is data service the direction of the next generation data center?
猜你喜欢
随机推荐
Technical dry goods | reproduce iccv2021 best paper swing transformer with Shengsi mindspire
Common operations of JSP
不出网上线CS的各种姿势
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
Margin left: -100% understanding in the Grail layout
Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
TCP cumulative acknowledgement and window value update
Vertx's responsive MySQL template
UA camouflage, get and post in requests carry parameters to obtain JSON format content
【LeetCode】2. Valid Parentheses·有效的括号
【MySQL 11】怎么解决MySQL 8.0.18 大小写敏感问题
IPv4 address
Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
为什么说数据服务化是下一代数据中台的方向?
Leetcode 213: 打家劫舍 II
Common architectures of IO streams
Jeecg menu path display problem
Technology dry goods | luxe model for the migration of mindspore NLP model -- reading comprehension task
Lombok cooperates with @slf4j and logback to realize logging









