当前位置:网站首页>Go basic part study notes
Go basic part study notes
2022-07-31 16:50:00 【Meme_xp】
函数和方法的区别
在Go语言中,函数和方法不太一样,有明确的概念区分.其他语言中,比如Java,一般来说函数就是方法,方法就是函数﹔但是在Go语言中,A function is a method that does not belong to any struct by type,也就是说函数是没有接收者的;而方法是有接收者的.
方法
func (t *T )add (a, b int) int {
return a + b
}
其中TIt is a custom Ao-type powerhouse structure.基础类型int等
函数
func add(a, b int) int {
return a + b
}
goA difference between method value receivers and pointer receivers
结论:
If the receiver of the method is指针类型,Whether the caller is an object or a pointer to an object,修改的都是对象本身,会影响调用者;
If the receiver of the method is值类型,无论调用者是对象还是对象指针,修改的都是对象的副本,不影响调用者;
package main
import "fmt"
type Person struct {
age int
}
//如果实现了接收者是指针类型的方法,will implicitly also implement that the receiver is a value typeIncrAge1方法.
//会修改age的值
func (p *Person) IncrAge1( ) {
p.age += 1
}
//如果实现了接收者是值类型的方法,Will implicitly also realize that the receiver is a pointer typeIncrAge2方法.//不会修改age的值
func (p Person) IncrAge2( ) {
p.age += 1
}
//如果实现了接收者是值类型的方法,Will implicitly also realize that the receiver is a pointer typeGetAge方法.
func (p Person) GetAge( ) int i{
return p.age
}
func main() {
//p是值类型
p := Person{
age: 10}
//A value type calls a method whose receiver is a pointer type
p.IncrAge1()
fmt.Println(p.GetAge( ))
//A value type calls a method whose receiver is a value type
p.IncrAge2()
fmt.Println(p.GetAge( ))
//p2是指针类型
p2:=&Person{
age:20}
//指针类型,The caller's receiver is a method of type pointer
p2.IncrAge1()
fmt.Println(p2.GetAge( ))
//A value type calls a method whose receiver is a value type
p2.IncrAge2()
fmt.Println(p2.GetAge( ))
Usually the reason we use pointer types as receivers of methods:
1.Using a pointer type can modify the caller's value.
2.Using a pointer type avoids copying the value every time the method is called,在值的类型为大型结构体时,这样做会更加高效.
goIs it safe to return a local variable from a function??
是安全的,but will escape the memory,allocated on the heap!!!
goFunction parameter passing is pass-by-value or pass-by-value
Go语言中所有的传参都是值传递《传值),都是一个副本,一个拷贝.
If parameter is a reference type(int、 string、struet等这些),In this way, the original content data cannot be modified in the letter.;如果是引用类型 指针、map、slice、chan等这些),这样就可以修改原内容数据.
是否可以修改原内容数据,和传值、传引用没有必然的关系.在C++中,传引用肯定是可以修改原内容数据的,在Go语言里,虽然只有传值,但是我们也可以修改原内容数据,因为参数是引用类型
传递slice也是值传递,But what is passed is a reference type,因为sliceThe bottom layer is like this
Pass it directly, although the value of the slice can be modified,但是没法修改len和cap,只有传sliceaddress can be modifiedlen和cap
map,chanEssentially a pointer,虽然是值传递,But you can still change the value
Reference types and pass by reference are2个概念,切记!!!
defer的原理
定义:
deferAllows us to defer certain function calls,defer actual execution until the current function returns.defer与panic和recover结合,形成了GoLanguage-style exceptions and catching mechanisms.
使用场景:
defer语句经常被用于处理成对的操作,as the file handle is closed、连接关闭、释放锁
优点:
方便开发者使用
缺点:
有性能损耗
实现原理:
Go1.14The compiler willdeleriThe function is inserted directly at the end of the function,Don't need to list and the copy on the stack,性能大幅提升.把delerThe function is expanded within the current letter and called directly,这种方式被称为open coded defer
注意:
2.panic后的defer函数不会被执行(遇到panicIf there is no catch mistakes,the function will stop immediately)
3. panic没有被recover时,抛出的panic到当前goroutine最When the upper function,The top directly abnormal program termination
package main
import "fmt"
func F() {
defer func(){
fmt.Println(""b")
}()
panic("a"")
}
//A subroutine is thrownpanic没有recover时,When the upper function,程序直接异常终止
func main(){
defer func(){
fmt.Println(""c"")
}()
F()
fmt.Println("继续执行")
}
//b
//c
//panic: a
4. panic有被recover时,当前goroutineThe top-level function executes normally
package main
import "fmt"
func F() {
defer func() {
if err := recover() ; err != nil {
fmt.Println("捕获异常: ",err)
}
fmt.Println(""b)
}()
panic("a")
}
func main(){
defer func(){
fmt.Println("c")
}()
F()
fmt.Println("继续执行")
}
//捕获异常: a
// b
//继续执行
// c
make和nwe函数
Correct it firstmake和new是内置函数,不是关键字
变量初始化,一般包括2步,变量声明+变量内存分配,var关键字就是用来声明变量的, new和makeThe function is mainly used to allocate memory
varVariables declared value types,系统会默认为他分配内存空间,并赋该类型的零值.such as boolean、数字、字符串、结构体.If a variable of a pointer type or a reference type,系统不会为它分配内存,默认就是ni1.此时如果你想直接使用,那么系统会抛异常,After memory allocation must be done,才能使用.
new和 make两个内置函数,Mainly used to allocate memory space,有了内存,Variables can be used,主要有以下2点区别:
1.使用场景区别:
make只能用来分配及初始化类型为slice、map、chan的数据.
new可以分配任意类型的数据,并且置零.
2.返回值区别:
make函数原型如下,返回的是slice、map、chan类型本身
这3type is a reference type,there is no need to return their pointers
func make(t Type,size ...Integer Type)Type
new函数原型如下,返回一个指向该类型内存地址的指针
func new(Type)*Type
边栏推荐
- 【C语言】LeetCode27.移除元素
- Flex布局详解
- Implementing distributed locks based on Redis (SETNX), case: Solving oversold orders under high concurrency
- [TypeScript] In-depth study of TypeScript type operations
- 研发过程中的文档管理与工具
- 每日练习------随机产生一个1-100之间的整数,看能几次猜中。要求:猜的次数不能超过7次,每次猜完之后都要提示“大了”或者“小了”。
- 你辛辛苦苦写的文章可能不是你的原创
- Flutter set the background color of the statusbar status bar and APP method (AppBar) internal consistent color.
- useragent在线查找
- Flutter gets the height of the status bar statusbar
猜你喜欢
研发过程中的文档管理与工具
Huawei's top engineers lasted nine years "anecdotal stories network protocol" PDF document summary, is too strong
【TypeScript】深入学习TypeScript类型操作
研发过程中的文档管理与工具
【C语言】LeetCode27.移除元素
flowable工作流所有业务概念
组合学笔记(六)局部有限偏序集的关联代数,Möbius反演公式
深度学习机器学习理论及应用实战-必备知识点整理分享
selenium的常见方法及使用
EF Core 2.2中将ORM框架生成的SQL语句输出到控制台
随机推荐
2020 WeChat applet decompilation tutorial (can applet decompile source code be used)
npm安装时卡在sill idealTree buildDeps,npm安装速度慢,npm安装卡在一个地方不动
IP protocol from 0 to 1
How C programs run 01 - the composition of ordinary executable files
2022年必读的12本机器学习书籍推荐
Golang 切片删除指定元素的几种方法
无主复制系统(3)-Quorum一致性的局限性
SHELL内外置命令
Implementing DDD based on ABP
【C语言】LeetCode27.移除元素
TestCafe总结
网站漏洞修复服务商关于越权漏洞分析
无主复制系统(1)-节点故障时写DB
Golang go-redis cluster模式下不断创建新连接,效率下降问题解决
selenium的常见方法及使用
[pytorch] pytorch automatic derivation, Tensor and Autograd
牛客 HJ18 识别有效的IP地址和掩码并进行分类统计
SringMVC中个常见的几个问题
A common method and the use of selenium
你辛辛苦苦写的文章可能不是你的原创