search
HomeBackend DevelopmentGolangThere are several types of variables in Go language
There are several types of variables in Go languageJan 10, 2023 am 11:34 AM
variablegolanggo language

There are three types of variables: 1. Variables defined within a function are called local variables, and their scope is limited to the inside of the function; local variables do not always exist, they only exist after the function that defines them is called. This local variable will be destroyed after the function call ends. 2. Variables defined outside the function are called global variables. They only need to be defined in one source file and can be used in all source files; the global variable declaration must start with the var keyword. If you want to use the global variable in an external package The first letter of a variable must be capitalized. 3. The variables in the function definition are called formal parameters.

There are several types of variables in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Go language is a statically typed language, so variables (variables) have clear types, and the compiler will also check the correctness of the variable type. In mathematical concepts, a variable represents a number that has no fixed value and can be changed. But from a computer system implementation perspective, a variable is one or more segments of memory used to store data.

A variable (constant, type or function) has a certain scope in the program, which is called scope.

Understanding the scope of variables is more important for us to learn the Go language, because the Go language will check whether each variable has been used during compilation. Once an unused variable appears, a compilation error will be reported. . If you cannot understand the scope of variables, it may cause some unexplained compilation errors.

According to the different definition locations of variables, they can be divided into the following three types:

  • Variables defined within a function are called local variables

  • Variables defined outside the function are called global variables

  • Variables in the function definition are called formal parameters

Let’s talk about them below introduce.

Local variables

Variables declared/defined inside a function are called local variables, and the scope of local variables is limited to the inside of the function. Variables defined inside the function, parameters and return values ​​of the function, variables used inside the if and for structures, etc. are all local variables.

Local variables do not always exist. They only exist after the function that defines them is called. This local variable will be destroyed after the function call ends.

[Example] The following main() function uses local variables a, b, and c.

package main
import (
    "fmt"
)
func main() {
    //声明局部变量 a 和 b 并赋值
    var a int = 3
    var b int = 4
    //声明局部变量 c 并计算 a 和 b 的和
    c := a + b
    fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
}

There are several types of variables in Go language

Use {} to limit the scope of variables

package main
import "fmt"
func main() {
	{
		name := "HaiCoder"
		fmt.Println("Name =", name)
	}
}

There are several types of variables in Go language

##We use { } Limit the scope of the variable name to {}, that is, the scope of the variable name at this time is only within {}, and name is a local variable.

Note: If the variable is accessed outside the scope of the variable, the program will report an error

package main
import "fmt"
func main() {
	for i := 0; i < 3; i++{
		fmt.Print(i)
		fmt.Print(" ")
	}
	fmt.Print(i)
}

There are several types of variables in Go language

We define a local variable i inside the for loop and use it, At this time, the scope of variable i is limited to the {} inside the for loop. Finally, when we access the variable i outside {} of the for loop, the program reports an error because the variable i exceeds the scope.

Global variables

The variables declared outside the function are called global variables. Global variables only need to be defined in a source file. It can be used in all source files. Of course, source files that do not contain this global variable need to use the "import" keyword to introduce the source file where the global variable is located before they can use this global variable.

Global variable declarations must begin with the var keyword. If you want to use the global variable in an external package, the first letter must be capitalized.

[Example] In the following code, line 6 defines the global variable c.

package main
import "fmt"
//声明全局变量
var c int
func main() {
    //声明局部变量
    var a, b int
    //初始化参数
    a = 3
    b = 4
    c = a + b
    fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
}

There are several types of variables in Go language

Note: The names of global variables and local variables in Go language programs can be the same, but local variables in the function body will be given priority.

package main
import "fmt"
//声明全局变量
var a float32 = 3.14
func main() {
    //声明局部变量
    var a int = 3
    fmt.Printf("a = %d\n", a)
}

There are several types of variables in Go language

Formal parameters

When defining a function, the variables in parentheses after the function name are called formal parameters (referred to as formal parameters). Formal parameters will only take effect when the function is called, and will be destroyed after the function call is completed. When the function is not called, the formal parameters of the function do not occupy actual storage units and have no actual values.

Formal parameters will be used as local variables of the function.

[Example] Line 21 of the code below defines the formal parameters a and b.

package main
import (
    "fmt"
)
//全局变量 a
var a int = 13
func main() {
    //局部变量 a 和 b
    var a int = 3
    var b int = 4
    fmt.Printf("main() 函数中 a = %d\n", a)
    fmt.Printf("main() 函数中 b = %d\n", b)
    c := sum(a, b)
    fmt.Printf("main() 函数中 c = %d\n", c)
}
func sum(a, b int) int {
    fmt.Printf("sum() 函数中 a = %d\n", a)
    fmt.Printf("sum() 函数中 b = %d\n", b)
    num := a + b
    return num
}

There are several types of variables in Go language

【相关推荐:Go视频教程编程教学

The above is the detailed content of There are several types of variables in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言是否需要编译go语言是否需要编译Dec 01, 2022 pm 07:06 PM

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

go语言能不能编译go语言能不能编译Dec 09, 2022 pm 06:20 PM

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

golang map怎么删除元素golang map怎么删除元素Dec 08, 2022 pm 06:26 PM

删除map元素的两种方法:1、使用delete()函数从map中删除指定键值对,语法“delete(map, 键名)”;2、重新创建一个新的map对象,可以清空map中的所有元素,语法“var mapname map[keytype]valuetype”。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools