Table of Contents
Go function memory allocation diagram" >Go function memory allocation diagram
Verification" >Verification
Result
" >Result
Essence
" >Essence
function Scope
" > function Scope
Global variables" >Global variables
小试牛刀" >小试牛刀
var引发的问题" >var引发的问题
使用const解决问题" >使用const解决问题
总结
" >总结
局部变量" >局部变量
defer
" >defer
一个defer" >一个defer
多个defer
" >多个defer
defer的作用" >defer的作用
panic和recover" >panic和recover
panic" >panic
recover" >recover
注意" >注意
Home Backend Development Golang An article to help you understand the basic functions of Go language (Part 2)

An article to help you understand the basic functions of Go language (Part 2)

Jul 25, 2023 pm 02:17 PM
go language

Go function memory allocation diagram

Go's function memory allocation is a bit like heap allocation, but it is not essentially the same.

An article to help you understand the basic functions of Go language (Part 2)

It can be understood that like heap memory, the stack stores the address of the heap.

Verification

Code

package main


import "fmt"




func say() string {
    return "ok"
}


func main() {
    fmt.Printf("say栈上的内容:%p\n",say)
}
Copy after login

Result

An article to help you understand the basic functions of Go language (Part 2)

Essence

An article to help you understand the basic functions of Go language (Part 2)

function Scope

#The issue of scope may have been raised more or less before, so let’s review it again.

Global variables

Global variables are variables defined outside all functions. The variables will always exist until the program ends.

当然,任何函数都可以访问全局变量。

注:全局变量尽量全部用大写。

小试牛刀

package main


import "fmt"




var NAME = "张三"
func say() string {
    fmt.Println(NAME)
    return "ok"
}


func main() {
    say()
    fmt.Println(NAME)
}
Copy after login

结果:

An article to help you understand the basic functions of Go language (Part 2)

上述可能会有个问题,全局变量,全局变量,大家共用一个,要是谁傻不拉几修改了不就完蛋了,整个程序都凉了。

var引发的问题

就像这样。

package main


import "fmt"


var NAME = "张三"


func say() string {
    fmt.Println(NAME)
    NAME = "李四"
    return "ok"
}


func main() {
    say()
    fmt.Println(NAME)
}
Copy after login

结果:

An article to help you understand the basic functions of Go language (Part 2)

这不就完犊子了吗???所以,一定要有解决办法。

使用const解决问题

解决办法:使用常量定义全局变量。

package main


import "fmt"


const NAME = "张三"


func say() string {
    fmt.Println(NAME)
    //NAME = "李四"//会报错:cannot assign to NAME
    return "ok"
}


func main() {
    say()
    fmt.Println(NAME)


}
Copy after login

总结

在定义全局变量时,需要用const修饰,并且变量名全部大写。

局部变量

局部变量,局部变量就是在某个函数内定义的变量,只能在自己函数内使用。

更专业点,在{}内定义的,只能在{}内使用,for同理。

代码

package main


import (
    "fmt"
)


func say() string {
    var name = "张三"
    fmt.Println(name)
    return "ok"
}


func main() {
    say()
    //fmt.Println(name)//会报错:undefined: name
    //for同理
    for i := 0; i <= 1; i++ {
        var c = "66"
        fmt.Println(c) //66
}
    //fmt.Println(c)//会报错:undefined: c
}
Copy after login

defer

在Go中,defer语句,可以理解为在return之前执行的一个语句。

如果函数没有return,会有一个默认的return,只是看不见而已。

一个defer

代码

package main


import "fmt"


func say() {
    //defer尽量往前放
    defer fmt.Println("我是666")
    fmt.Println("你们都是最棒的")
}


func main() {
    say()
}
Copy after login

执行结果

An article to help you understand the basic functions of Go language (Part 2)

多个defer

代码

package main


import "fmt"


func say() {
    //defer尽量往前放
    defer fmt.Println(1)
    defer fmt.Println(2)
    defer fmt.Println(3)
    fmt.Println("你们都是最棒的")
}


func main() {
    say()
}
Copy after login

执行结果

An article to help you understand the basic functions of Go language (Part 2)

可以发现,defer的执行结果是反着的。

结论:先执行的defer,会最后执行,最后执行的defer,会最先执行,有点像栈,先进后出

defer的作用

通常来说,defer会用在释放数据库连接,关闭文件等需要在函数结束时处理的操作。

这里暂时先不举例子。


panic和recover

这俩,可以理解为Python中的tryraise,因为在Go中,是没有try的,是不能像其他语言一样,try所有异常。

应用场景:比如某个web,在启动时,数据库都没连接成功,必定要启动失败,就像电脑,没有电源必不能开机一样。

panic

先看一下语法吧

package main


import "fmt"


func say() {
    var flag = true
    if flag{
        //引发错误,直接中断程序的错误
        panic("OMG,撤了撤了,必须撤了")
}
}


func main() {
    say()
    fmt.Println("继续呀...")//不会执行,程序挂了
}
Copy after login

执行效果

An article to help you understand the basic functions of Go language (Part 2)

可以看淡,继续呀就没打印,程序直接挂了,但是上述好像并没有解决这个问题。

recover

尝试捕捉

代码

package main


import "fmt"


func say() {
  //匿名函数,defer执行的是一个匿名函数
  defer func() {
    var err = recover()
    //如果有panic错误,err!=nil,在此处步骤,尝试恢复
    if err != nil {
      fmt.Println("尝试恢复...")
    }
  }()
  var flag = true
  if flag {
    panic("OMG,撤了撤了,必须撤了")
  }
}


func main() {
  say()
  fmt.Println("继续呀...")
}
Copy after login

执行结果

An article to help you understand the basic functions of Go language (Part 2)

可以看到,如果recover捕捉了,并且没有panic,程序就会继续正常执行。

注意

defer必须在panic语句之前。

recover必须配合defer使用。

The above is the detailed content of An article to help you understand the basic functions of Go language (Part 2). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles