当前位置:网站首页>An article learns variables in go language
An article learns variables in go language
2022-07-04 15:15:00 【1024 questions】
1. identifier
2. keyword
3. Variable
3.1 Go Declaration of variables in language
3.2 Batch statement
3.3 Initialization of a variable
3.4 Short variable declaration
3.5 Anonymous variables
4. Constant
5.iota
summary
1. identifierIn programming language, identifier is a word with special meaning defined by programmer , For example, variable name , Constant names , function .bc,_123,a1232
2. keywordKeywords are pre-defined identifiers with special meanings in programming languages , Keywords and reserved words are not recommended as variable names
Go In language 25 Key words
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
also 37 A reserved word
3. VariableConstants: true false iota nil
Types: int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
float32 float64 complex128 complex64
bool byte rune string errorFunctions: make len cap new append copy close delete
complex real imag
panic recover
The function of variables is to store data , Different variables may hold different data types , After more than half a century of development , Programming languages have basically formed a set of fixed types , The data types of common variables are : integer 、 floating-point 、 Boolean, etc
Go Every variable in a language has its own type , And variables must be declared before they can be used
3.1 Go Declaration of variables in languageDeclaration format
var Variable name Variable type
Variables are declared with keywords var start , The variable type is placed after the variable , No semicolon is required at the end of the line , for instance
var name stringvar age intvar isOk bool
3.2 Batch statement Every time you declare a variable, you need to write var Keywords will be more cumbersome ,go The language also supports batch variable declaration :
var ( a string b int c bool d float32)
3.3 Initialization of a variable Go When languages declare variables , It will automatically initialize the memory area corresponding to the variable , Each variable is initialized to the default value of its type . For example, the default values for integer and floating-point variables are 0, The default value of string variable is empty string , Boolean variables default to false. section 、 function 、 The default value of pointer variable is nil
func main() {var (test01 stringtest02 inttest03 booltest04 float32)fmt.Println(test01, test02, test03, test04)}
0 false 0
Of course, we can also specify an initial value for a variable when it is declared . The standard format for variable initialization is as follows :
var Variable name type = expression
Example
var name string="wql"var age int =18
Or initialize more than one variable at a time
var name,age="wql",20
Sometimes we omit the types of variables , At this time, the compiler will deduce the type of the variable according to the value to the right of the equal sign to complete the initialization
var name = "wql"var age = 18
3.4 Short variable declaration Inside the function , You can use a simpler := Method to declare and initialize variables
package main// Tell the program that it needs fmt package ,fmt Functions with printouts import "fmt"var n intfunc main() {b := 123fmt.Println(b)}
3.5 Anonymous variables When using multiple assignments , If you want to ignore a value , You can use anonymous variables (anonymous variable). Anonymous variables are underlined, for example
package main// Tell the program that it needs fmt package ,fmt Functions with printouts import "fmt"func main() {x, _ := foo()_, y := foo()fmt.Println("x=", x)fmt.Println("y=", y)}func foo() (int, string) {return 10, "wql"}
123 123hello wqlx= 10y= wql
Anonymous variables do not take up the namespace , Memory will not be allocated , So there is no duplicate declaration between anonymous variables
matters needing attention
Every statement outside a function must start with a keyword (var、const、func etc. )
:= Cannot be used outside a function
_ It is often used for space occupying , Indicates the ignored value
4. ConstantRelative to variables , Constant is a constant value , It is used to define which values will not be changed during the running of the program . The declaration of constants is very similar to that of variables , Knowledge handle var Instead of const, Constants must be defined with values
const pi = 3.12
const e = 2.7
fmt.Println(pi, e)
1
2
3
In the statement pi and e After these two constants , Their values can no longer be changed during the entire program run
Multiple constants can also be declared together
const( p1 = 2 p2 = 4 )
const When multiple constants are declared at the same time , If the value is omitted, it means that it is the same as the value in the previous line , for example
const( p3 = 200 p4 p5 )
In the above example p3,p4,p5 The values are all 200
5.iotaiota yes go Constant counter of language , Can only be used in constant expressions
iota stay const The keyword will be reset to 0,const Every new line of constant declaration in will cause iota Count once ,iota It can be understood as const Line index in statement block , Use iota Can simplify the definition of , Useful when defining enumerations
const ( n1 = iota //0 n2 //1 n3 //2 n4 //3 ) fmt.Println(n1, n2, n3, n4)
0 1 2 3
` Several common iota example :
` Use underscores to skip some values
const ( n1 = iota //0 n2 //1 _ n4 //3 )
iota Make a statement to jump in the middle const ( n1 = iota //0 n2 = 100 //100 n3 = iota //2 n4 //3 )
That is, whether there is an initial value ,iota all +1, A constant with an initial value is an initial value , No initial value is iota+1
const ( _ = iota KB = 1 << (10 * iota) MB = 1 << (10 * iota) GB = 1 << (10 * iota) TB = 1 << (10 * iota) PB = 1 << (10 * iota) )
Multiple iota It's defined on one line
const ( a, b = iota + 1, iota + 2 //1,2 c, d //2,3 e, f //3,4 )
therefore iota There are two characteristics
When I meet const Appearance is set as 0
Every new line is +1
summaryHere is an article about learning GO This is the introduction of variables in language , More about GO For the content of language variables, please search the previous articles of SDN or continue to browse the relevant articles below. I hope you will support SDN more in the future !
边栏推荐
- Go zero micro service practical series (IX. ultimate optimization of seckill performance)
- Unity脚本介绍 Day01
- Unity update process_ Principle of unity synergy
- Huawei cloud database DDS products are deeply enabled
- Unity动画Animation Day05
- Dialogue with ye Yanxiu, senior consultant of Longzhi and atlassian certification expert: where should Chinese users go when atlassian products enter the post server era?
- On the implementation plan of MySQL explain
- What is the future of the booming intelligent Internet of things (aiot) in recent years?
- 对话龙智高级咨询顾问、Atlassian认证专家叶燕秀:Atlassian产品进入后Server时代,中国用户应当何去何从?
- 开源人张亮的 17 年成长路线,热爱才能坚持
猜你喜欢
Building intelligent gray-scale data system from 0 to 1: Taking vivo game center as an example
产品好不好,谁说了算?Sonar提出分析的性能指标,帮助您轻松判断产品性能及表现
Intelligent customer service track: Netease Qiyu and Weier technology play different ways
Unity脚本常用API Day03
压力、焦虑还是抑郁? 正确诊断再治疗
Memory management summary
Details of FPGA underlying resources
Leetcode 1200 minimum absolute difference [sort] The Path of leetcode for heroding
TechSmith Camtasia studio 2022.0.2 screen recording software
Redis sentinel mode realizes one master, two slave and three Sentinels
随机推荐
Width accuracy
They are all talking about Devops. Do you really understand it?
[learning notes] matroid
重排数组
Guitar Pro 8win10 latest guitar learning / score / creation
Optimization method of deep learning neural network
输入宽度!
Who the final say whether the product is good or not? Sonar puts forward performance indicators for analysis to help you easily judge product performance and performance
近一亿美元失窃,Horizon跨链桥被攻击事件分析
[differential privacy and data adaptability] differential privacy code implementation series (XIV)
unity update 协程_Unity 协程的原理
Implementation of macro instruction of first-order RC low-pass filter in signal processing (easy touch screen)
华为云数据库DDS产品深度赋能
Introduction of text mining tools [easy to understand]
%S format character
数据湖治理:优势、挑战和入门
Introduction to asynchronous task capability of function calculation - task trigger de duplication
03 storage system
Enter the width!
一篇文章学会GO语言中的变量