Exploring Go Language Variables and Identifiers: Flexible Storage of Data

Table of contents

identifier

Naming rules

naming convention

Examples of identifier usage

variable

Common variable types

Variable declaration and assignment

Initialization of variables

Standard statement

Batch declaration

type inference

anonymous variable

Sample code

Summarize


 

picture

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

Original text: Exploring Go language variables and identifiers: Flexible storage of data

Since many fans left messages in the background to inquire about Go development technical information, I quickly took some time on weekends and late at night to plan the content of articles about the Go series. I think it can be divided into three stages. The first stage is The entire syntax of Go. The second stage is the advanced content of Go involving distributed high concurrency. The third stage is back-end development, web framework and database operation part.

In previous articles, we also gave a general introduction to Go, including some open source projects and learning materials. For details, please refer to the recommended reading at the end of the article.

There are nearly 60 articles in the first stage, and the general contents are as follows:

【Go first stage】

  1. "Advanced features, development trends, and recommended most popular open source projects of Go language"

  2. "Go 1.21 stable version and new features detailed explanation"

  3. "Detailed Explanation of Go's Multi-Terminal Development Environment and Compiler Construction (Pictures and Text)"

  4. "Go Coding, Standards First"

  5. "Detailed introduction to the development of Go code packages and custom packages"

  6. "Go Command Operation Summary Tutorial"

  7. "Summary of Print Output Methods in Go Language"

  8. "Exploring Go Language Variables: Flexible Storage of Data"

  9. "Decryption of Go Language Constants: Constant Values"

  10. "In-depth understanding of data types in Go language"

  11. "The Secret of String Operations in Go Language: Efficiently Processing Text"

  12. "Comprehensive analysis and pit digging of Go's process control (if, for, switch, goto)"

  13. "String Traversal Techniques in Go: Easily Manipulate Text"

  14. "Go language gconv type conversion: seamless conversion of data"

  15. "Using strconv to convert Go's int, float, and string types to each other: Flexible conversion of data types"

  16. "Go's Operator Decryption: Exploring the Secrets of Computation"

  17. "Expression Analysis in Go: Understanding the Core of Code"

  18. "Go's slice technique: Flexible operation of ordered collections"

  19. "In-depth understanding and in-depth analysis of Go language slices (Slice): Exploring the underlying mechanism"

  20. "Go's Slice Tips: Improving Code Efficiency"

  21. "Go's Range Traversal Revealed: Master Iteration Skills and Efficiently Process Data Collections"

  22. "Go's rune analysis: in-depth understanding of character processing"

  23. "The Secret of Map (Collection) Operation in Go Language: Mastering Efficient Mapping Skills"

  24. " Go Language Keyword Analysis: Understanding Key Code Elements "

  25. "Go Language Mapping Skills: Flexible Operation of Data Collections"

  26. "Go language assignment and (deep) copy analysis: in-depth analysis of data processing"

  27. "Parsing Arrays in Go Language: Efficiently Processing Ordered Data"

  28. "Go's initial use of arrays and how to use them as function parameters"

  29. "Comparison of the Differences and Features of Go's Built-in Data Structures Array, Slice, and Map"

  30. "The Art of Error Handling in Go: An In-depth Study of the Error Handling Mechanism of Go Language"

  31. "A Brief Discussion on Golang's Controversial Error: Discussing Its Advantages, Disadvantages and Application Scenarios"

  32. "The Wonderful World of Go Pointers: Analyzing Pointer Usage in Go Language"

  33. "The Charm of Go Methods: Mastering the Skills of Using Methods in Go Language"

  34. "Exploring Go Modular Programming: The Design and Use of Modules in Go Language"

  35. "The Wonderful Journey of Go Functions: In-depth Understanding of Functional Characteristics in Go Language"

  36. "The Difference Between Go Functions and Methods: Revealing Their Commonalities and Differences"

  37. "The Charm of Go Recursive Functions: Exploring the Magical Use of Recursion in Go Language"

  38. "The secret of Go's efficient built-in functions: Go language built-in functions commonly used in development"

  39. "Exploration of Go Functional Programming: Advantages, Disadvantages and Practical Explanation of Module Application"

  40. "The Charm of Go's Higher-Order Functions: Mastering Functional Programming in Go Language"

  41. "Detailed introduction to the role and use of Go's higher-order functions"

  42. "The Wonderful World of Go Interfaces: In-depth Understanding of Interface Features in Go Language"

  43. "Black Box Analysis of Go Garbage Collection: Exploring the Garbage Collection Mechanism in Go Language"

  44. "Go Quickly Integrate Log Module: Log Module Integration Guide in Go Language Framework"

  45. "Go Structure (struct) Analysis: Master the use skills of structures in Go language"

  46. "Go Performance Testing Techniques Revealed: Optimizing the Performance of Go Language Programs"

  47. "Go Debugging & Unit Testing: Debugging and Testing Skills in Go Language Development"

  48. "Comprehensive Analysis of Go Time Operations: Master the Skills of Time Processing"

  49. "The underlying implementation of Go function closures: an in-depth discussion of the principles of closures in the Go language"

  50. "The Secret of Go Concurrency Safety: In-depth understanding of the implementation principle of sync.Map, the concurrency safety in Go language"

  51. "The Wonderful World of Context: Basics of Go Concurrent Programming: What is context and exploring the application and practice of context in Go language"

  52. "Go package manager tool mod"

  53. "Comparison of package management tools in Go language: Go Modules and dep"

  54. "Go dependency management tool dep"

  55. "Analysis of Go Memory Management and Garbage Collection Mechanism"

  56. "How to use the logging package in Go"

  57. "Communication between Go Executors"

  58. "Go Coroutines: Parallel Computing"

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

picture

Go language is a statically typed programming language, and variables are used to store and manipulate data in Go. In Go, variables must be declared before they are used, and each variable has a specific type.

The data during program running is stored in memory. If we want to operate a certain data in the code, we need to find the variable in the memory. But if we directly operate the variable through the memory address in the code, The readability of the code will be very poor and error-prone, so we use variables to save the memory address of this data. In the future, we can find the corresponding address and data in the memory directly through this variable.

Go language is a statically typed programming language, so when using variables, you need to declare their type first. Variables are one of the most basic components of a program in the Go language. They are used to store data in the program.

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

 In this article, I will introduce in detail the identifiers, variables, and variable naming rules in the Go language, including variable declaration, assignment, type deduction, and common variable types, and demonstrate it using code examples.

The next article will summarize and introduce the scope, life cycle, and type conversion of Go.

identifier

In programming languages, identifiers are words with special meanings defined by programmers, such as variable names, constant names, function names, etc. Identifiers in Go language consist of alphanumeric characters and _ (underscore), and can only start with letters and _. To give a few examples: abc, _, _123, a123.

Go language identifiers are names used to name program entities such as variables, constants, functions, and types. In the Go language, identifiers have some rules and conventions. Let’s learn more about them below.

Naming rules

In the Go language, the naming of identifiers (variables) needs to follow some rules. The rules are as follows:

1. An identifier (variable name) consists of one or more letters, numbers, or underscores.

2. The first character of the identifier (variable name) must be a letter or underscore, not a number.

3. Identifiers (variable names) are case-sensitive. For example, name and Name are different identifiers (variables).

4. Go language keywords cannot be used as identifiers (variable names), such as if, for, etc.

5. The identifier (variable name) should be descriptive and be able to clearly express the meaning of the variable (see the name to know the meaning).

For the introduction and use of keywords, you can refer to the public account CTO Plus article " Just read this article to summarize the functions, characteristics and usage of Go keywords in detail ".

Generally speaking, the naming style of Go language adopts camel case naming method, that is, the first letter is lowercase, and the first letter of subsequent words is capitalized, such as userName and studentAge.

naming convention

In addition to naming rules, the Go language also has some naming conventions used to improve the readability and maintainability of the code.

1. Use camel case naming: Go language recommends using camel case naming to name identifiers. CamelCase nomenclature is divided into two forms: CamelCase nomenclature with the first letter in lowercase (such as myVariable) is used for private variables and local variables, and camelCase nomenclature with the first letter in uppercase (such as MyVariable) is used for public variables and global variables.

2. Use meaningful names: Identifier names should be descriptive and clearly express their purpose and meaning. Avoid using single letters or meaningless names.

3. Follow naming conventions: Go language has some naming conventions, such as using single-character names for iteration variables (such as i, j, k), using err as the name of error variables, etc. Following these conventions can improve the readability of your code.

4. Avoid using abbreviations: Try to avoid using abbreviations to name identifiers unless the abbreviation is well-known. Using complete words improves the readability of your code.

Examples of identifier usage

Here are some examples of using Go language identifiers:

package main

import "fmt"

func myFunction(age int) int {
  var count int
  return count + age
}

func simple_variable() {
  var age int = 28
  var name string = "SteveRocket"

  fmt.Println("name:", name, "age:", age) // name: SteveRocket age: 28
  fmt.Println(myFunction(age))            // 28
}

func main() {
  simple_variable()
}
 
 

In the above example, we have used some identifiers such as age, name, myFunction and count. These identifiers follow the naming rules and conventions of the Go language, are descriptive, and are easy to understand and maintain.

Next, we introduce the declaration, assignment and naming rules of variables.

variable

The Go language is statically typed. Go variables must be declared first and then used. The type of the variable must be clear when declaring the variable. One significant difference between the Go language and other languages ​​is that the types of the Go language are behind the variables. For example, in C/C++ and Java, declaring a whole is generally written as int a = 1. In Go language, it needs to be written like this, as shown in the following code example:

func main() {
  var num int      // // 声明一个保存整型的变量num,如果没有赋值,默认为0
  fmt.Println(num) // 0

  var num2 int = 123 // 声明时赋值
  fmt.Println(num2)  // 123

  //因为 456 是 int 类型,所以赋值时,num3 自动被确定为 int 类型,所以类型名可以省略不写
  var num3 = 456    // 声明时赋值
  fmt.Println(num3) // 456

  var nick_name string  // 声明一个保存字符串类型的变量nick_name
  fmt.Println(nick_name) // 空字符串
  // 更简单的声明赋值
  name := "SteveRocket"
  fmt.Println(name) // SteveRocket

  var isNull bool  // 声明一个保存布尔类型的变量isNull,默认为false
  fmt.Println(isNull)
}
 
 

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

 

Common variable types

The function of variables (Variable) is to store data. Different types of variables may store different data types. Go language provides multiple data types for storing different types of data. Common variable types (data types) include:

  • Integer types: int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, etc.

  • Floating point number types: float32, float64.

  • Boolean type: bool, the value is true or false.

  • String type: string.

  • Character type: byte, used to represent ASCII characters.

For a detailed introduction to data types, follow the article "In-depth understanding of the data types of Go language" behind the public account CTO Plus

In addition to the above basic data types, the Go language also provides composite types, such as arrays, slices, maps, structures, etc., for storing multiple values ​​or values ​​of different types.

For a detailed introduction to composite data types, please pay attention to the article behind the official account CTO Plus:

  • "The Secret of Map (Collection) Operation in Go Language: Mastering Efficient Mapping Skills"

  • "Go's slice technique: Flexible operation of ordered collections"

  • "In-depth understanding and in-depth analysis of Go language slices (Slice): Exploring the underlying mechanism"

  • "Go's Slice Tips: Improving Code Efficiency"

  • "Go Language Mapping Skills: Flexible Operation of Data Collections"

  • "Parsing Arrays in Go Language: Efficiently Processing Ordered Data"

  • "Go's initial use of arrays and how to use them as function parameters"

  • "Comparison of the Differences and Features of Go's Built-in Data Structures Array, Slice, and Map"

Each variable in the Go language has its own type, and the variable must be declared before it can be used. Next, we will introduce the declaration and assignment of variables.

Variable declaration and assignment

In the Go language, the keyword var is used to declare a variable. When using the var keyword to declare a variable, you need to specify the name and type of the variable. The syntax is as follows:

var variable name type

For example, declare a variable age of type integer:

var age int

After a variable is declared, an initial value can be assigned to the variable through an assignment operation. Assignment uses the equal sign =, for example:

age = 25

You can also assign a value while declaring a variable, which is called initialization of the variable, for example:

var name string = "John"

Inside the function, it can be used.

In the Go language, the declaration of variables can be simplified using the var keyword, or using the simpler symbol := to declare and initialize variables (short variable declaration). When using the short declaration (:=) method, the keyword var and type declaration can be omitted, for example:

age := 25

name := "SteveRocket"

When using the := notation for simplification, the type of the variable is automatically deduced from the assigned value (the value on the right).

Variables in the Go language need to be declared before they can be used, and repeated declarations are not supported in the same scope. And Go language variables must be used after they are declared.

In Go language, variable assignment can be performed using the = symbol, for example:

age := 18

age = 20

When assigning values, please note that the type of the variable must be consistent with the type of the assigned value, otherwise a compilation error will occur.

At the same time, the Go language also supports multiple assignments, such as:

a, b := 1, 2

a, b = b, a

In the above code, we use multiple assignment to interchange the values ​​of a and b.

Complete code example:

package main

import "fmt"

// go语言中推荐使用驼峰命名
var studentName string

func variable() {
  Age := 30        // 变量区分大小写
  fmt.Println(Age) // 30

  age := 28
  fmt.Println(age) // 28
  age = 30         // 赋值
  fmt.Println(age) //30
  age = 25.0       // 重新赋值
  fmt.Println(age) // 25

  //在赋值时,需要注意变量的类型必须与所赋的值的类型一致,否则会导致编译错误。
  //age = 25.55  // cannot use 25.55 (untyped float constant) as int value in assignment (truncated)

  fmt.Println(age, Age) // 25 30
  age, Age = Age, age
  fmt.Println(age, Age) // 25 30
}

func main() {
  variable()
}
 
 

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

Initialization of variables

When the Go language declares a variable, it will automatically initialize the memory area corresponding to the variable. Each variable will be initialized to the default value of its type, for example:

  • The default value of integer variables is 0.

  • The default value of floating point variables is 0.0.

  • The default value of a string variable is the empty string "".

  • The default value of Boolean variables is false.

  • The default value of slices, functions, and pointer variables is nil.

func variable_default_value() {
  var name string
  var age int
  var isNull bool
  var salary float64
  // 切片
  var slice []int
  // 函数
  var fn func()
  // 指针变量
  var ptr *int
  fmt.Println(name, age, isNull, salary, slice, fn, ptr) // 输出结果:"" 0 false 0 [] <nil> <nil>
}
 
 

Note that these default values ​​only apply if the variable is not explicitly assigned a value when it is declared. If an initial value is explicitly assigned when declaring a variable, the variable will be initialized to that initial value. The standard format for batch variable initialization is as follows:

var variable name type = expression

var name2, age2, wechat = "SteveRocket", 28, "CTO Plus"

Standard statement

The variable declaration format of Go language is:

var variable name variable type

The variable declaration begins with the keyword var, the variable type is placed after the variable, and there is no need for a semicolon at the end of the line. for example:

var name string

var age int

var isNull bool

Batch declaration

It would be cumbersome to write the var keyword every time you declare a variable. Go language also supports batch variable declaration:

//Declare variables in batches

was (

   num1   int

   name   string

   age    int32

   isNull bool

   salary float32

)

type inference

Sometimes we will omit the type of the variable. In this case, the compiler will deduce the type of the variable based on the value on the right side of the equal sign to complete the initialization.

var name = "SteveRocket"

was age = 18

anonymous variable

When using multiple assignment, if you want to ignore a certain value, you can use an anonymous variable. Anonymous variables are represented by an underscore _, for example:

func annoymous_variable(salary float64) (int, string, bool, float64) {
  return 28, "SteveRocket", true, salary
}
func main() {
  age, _, sex, _ := annoymous_variable(0)
  fmt.Println(age, sex) // 28 true
  //_, _, _, _ := annoymous_variable(0)  // no new variables on left side of :=
  _, _, _, salary := annoymous_variable(0)
  fmt.Println(salary)
}
 
 

Anonymous variables do not occupy the namespace and do not allocate memory, so there are no repeated declarations between anonymous variables. They can also be used as a placeholder in Python.

Sample code

Here is a sample code using variables, as follows:

package main

import "fmt"

// 全局变量studentName  go语言中推荐使用驼峰命名
var studentName string

// 批量声明全局变量
// 声明全局变量建议使用批量声明,方便追加
var (
  num1   int
  name   string
  age    int32
  isNull bool
  salary float32
)

// 声明变量
var myName string
var myAge int
var isSex bool

// 批量初始化变量(一次初始化多个变量)
var name2, age2, wechat = "SteveRocket", 28, "CTO Plus"

func variable() {
  Age := 30        // 变量区分大小写
  fmt.Println(Age) // 30

  age := 28
  fmt.Println(age) // 28
  age = 30         // 赋值
  fmt.Println(age) //30
  age = 25.0       // 重新赋值
  fmt.Println(age) // 25

  //在赋值时,需要注意变量的类型必须与所赋的值的类型一致,否则会导致编译错误。
  //age = 25.55  // cannot use 25.55 (untyped float constant) as int value in assignment (truncated)

  fmt.Println(age, Age) // 25 30
  age, Age = Age, age
  fmt.Println(age, Age) // 25 30
}

func variable02() {
  // 非全局变量(局部变量)声明了就必须使用,不使用就无法编译通过(全局变量声明或初始化了不使用也可以编译通过)
  // 不使用报错:blog declared and not used
  var blog = "https://mp.weixin.qq.com/s/0yqGBPbOI6QxHqK17WxU8Q"
  fmt.Println(blog)

  //同一个作用域,不能重复声明同名变量
  //blog := "" // no new variables on left side of :=
  blog = "" // 但可以重新赋值
  fmt.Println(blog)

}
func variable_default_value() {
  var name string
  var age int
  var isNull bool
  var salary float64
  // 切片
  var slice []int
  // 函数
  var fn func()
  // 指针变量
  var ptr *int
  fmt.Println(name, age, isNull, salary, slice, fn, ptr) // "" 0 false 0 [] <nil> <nil>
}

func annoymous_variable(salary float64) (int, string, bool, float64) {
  // 匿名变量 是一个特殊的变量: _
  // 匿名变量使用_指定,用来作为一个占位符,匿名变量不占用命名空间,不会分配内存,所以匿名变量之间不存在重复声明
  return 28, "SteveRocket", true, salary
}

func main() {
  variable()
  variable02()
  variable_default_value()
  age, _, sex, _ := annoymous_variable(0)
  fmt.Println(age, sex) // 28 true
  //_, _, _, _ := annoymous_variable(0)  // no new variables on left side of :=
  _, _, _, salary := annoymous_variable(0)
  fmt.Println(salary)
}
 
 

In the above example, we fully demonstrated the declaration of variables, the use of anonymous variables, initialization of variables, type deduction of short variables, etc., as well as assigning initial values ​​to these variables through assignment operations, and using fmt.Println() The function prints the value of a variable to standard output.

For more information on how to use printout in Go language, please refer to this article on the public account CTO Plus: "Summary of printout methods in Go language"

For more related technical points about Go, please pay attention to the public account: CTO Plus’s subsequent posts. If you have any questions, please leave a message in the background for communication.

picture

Summarize

After the introduction of the above article, the following summarizes some notes on the use of variables:

Precautions

  • Every statement outside a function must start with a keyword (var, const, func, etc.).

  • := cannot be used outside a function.

  • _ is mostly used for placeholders, and the identification value can be ignored.

  • In the Go language, variables of different types are assigned default values ​​when declared. The default value of integer variables is 0, the default value of floating-point variables is 0.0, and the default value of string variables is the empty string "". The default value of Boolean variables is false, and the default value of slice, function, and pointer variables is nil.

  • If an initial value is explicitly assigned when declaring a variable, the variable will be initialized to that initial value and must be used in the code, otherwise a compilation error will occur.

In general, variables in the Go language are used to store and manipulate data and need to be declared before use. The variable is declared using the keyword var, and an initial value can be assigned to the variable through an assignment operation. The naming of variables needs to follow certain rules and should be descriptive. Go language provides multiple data types for storing different types of data. Through reasonable use of variables, data can be easily managed and manipulated.

At the same time, Go language identifiers are used to name program entities such as variables, constants, functions, and types. Identifiers have some naming rules and conventions, such as using camel case naming, using meaningful names, following naming conventions, etc. Following these rules and conventions can improve the readability and maintainability of your code.

I hope this article will help you understand the identifiers (variables) of the Go language!

Cloud native & microservice column
https://blog.csdn.net/zhouruifu2015/category_5704941

For more exciting news, follow my official account and learn and grow together.

picture

 

Guess you like

Origin blog.csdn.net/zhouruifu2015/article/details/133387867