Golang Variables#
1. Variables are the basic building blocks of a program#
- Regardless of which high-level programming language is used to write a program, variables are the basic building blocks of that program.
sum, sub are both variables
2. Introduction to Variables#
2.1 Concept of Variables#
A variable represents a data storage space in memory; you can think of a variable as a room number. Through the room number, we can find the room, and similarly, we can access the variable (value) through the variable name.
2.2 Steps to Use Variables#
- Declare a variable (also called: define a variable)
- Assign a value to the variable
- Use the variable
2.3 Quick Start Example for Variables#
Output:
2.4 Notes on Using Variables#
- A variable represents a storage area in memory
- This area has its own name (variable name) and type (data type)
Illustration:
- Three ways to use Golang variables
-
First: Specify the variable type; if not assigned a value after declaration, use the default value
-
Second: Determine the variable type based on the value (type inference)
-
Third: Omit var; note that the variable on the left side of := should not have been declared before, otherwise it will cause a compilation error
-
Multiple variable declarations
In programming, sometimes we need to declare multiple variables at once, Golang also provides such syntax. For example:
How to declare multiple global variables at once [Defining variables outside of functions in Go makes them global]:
-
The data value in this area can change continuously within the same type range (key point)
-
Variables cannot have the same name within the same scope (in a function or code block)
-
Variable = variable name + value + data type, please note this, the three elements of a variable
-
If a Golang variable is not assigned an initial value, the compiler will use the default value, for example, the default value of int is 0, the default value of string is an empty string, and the default value of float is 0.
2.5 Declaration, Initialization, and Assignment of Variables#
2.6 Use of the + Sign in Programs#
- When both sides are numeric, it performs addition.
- When both sides are strings, it performs string concatenation.
2.7 Basic Introduction to Data Types#
2.8 Integer Types#
2.8.1 Basic Introduction#
Simply put, it is used to store integer values, such as 0, -1, 2345, etc.
2.8.2 Various Types of Integers#
Unsigned types of int:
Explanation of other types of int:
2.8.4 Details of Using Integers#
- Golang's integer types are divided into: signed and unsigned; the size of int and uint depends on the system.
- The default declaration of Golang's integer type is int.
- How to check the byte size and data type of a variable in a program (commonly used)
- When using integer variables in Golang programs, follow the principle of using smaller space types, that is: use the smallest data type possible while ensuring the program runs correctly. [For example: age]
- bit: the smallest storage unit in a computer. byte: the basic storage unit in a computer. [More details on binary] 1 byte = 8 bits
2.9 Decimal Types/Floating Point Types#
2.9.1 Basic Introduction#
Decimal types are used to store decimals, such as 1.2, 0.23, -1.911.
2.9.2 Example Demonstration#
2.9.3 Classification of Decimal Types#
Explanation of the above image:
-
A simple explanation of how floating-point numbers are stored in machines: floating-point number = sign bit + exponent bit + mantissa bit. Note: Floating-point numbers are all signed.
-
The mantissa part may be lost, causing precision loss. -123.0000901
Note: float64 has higher precision than float32.
Note: If we want to save a number with high precision, we should choose float64. -
The storage of floating-point types is divided into three parts: sign bit + exponent bit + mantissa bit. During the storage process, precision may be lost.
2.9.4 Details of Using Floating Point Types#
- Golang floating-point types have fixed ranges and field lengths, which are not affected by the specific OS.
- The default declaration of Golang's floating-point type is float64.
- Floating-point constants have two representations:
Decimal form: e.g., 5.12, .512 (must have a decimal point)
Scientific notation: e.g., 5.1234e2 = 5.12 * 10 to the power of 2, 5.12E-2 = 5.12/10 to the power of 2
- Generally, float64 should be used because it is more precise than float32. [Recommended to use float64 in development]
2.10 Character Types#
2.10.1 Basic Introduction#
Golang does not have a dedicated character type; if you want to store a single character (letter), you generally use byte to save it. A string is a sequence of characters of fixed length connected together. Go's strings are made up of single bytes. In other words, traditional strings are composed of characters, while Go's strings are composed of bytes.
2.10.2 Example Demonstration#
Explanation of the above code:
- If the character we save is in the ASCII table, for example, [0-1, a-z, A-Z..], it can be directly saved to byte.
- If the character we save corresponds to a code value greater than 255, we can consider using int type to save it.
- If we need to output in character form, we need to format the output, i.e., fmt.Printf("%c", c1).
2.10.3 Details of Using Character Types#
- Character constants are enclosed in single quotes ('') for a single character. For example: var c1 byte = 'a', var c2 int = ' 中 ', var c3 byte = '9'.
- Go allows the use of escape characters '' to turn the following character into a special character constant. For example: var c3 char = '\n' // '\n' represents a newline character.
- The characters in Go are encoded using UTF-8. If you want to check the corresponding UTF-8 code value of a character, visit http://www.mytju.com/classcode/tools/encode_utf8.asp.
English letters - 1 byte, Chinese characters - 3 bytes. - In Go, a character is essentially an integer, and when output directly, it is the UTF-8 code value corresponding to that character.
- You can directly assign a number to a variable and then format the output with %c, which will output the Unicode character corresponding to that number.
- Character types can be operated on, equivalent to an integer, because they all correspond to Unicode codes.
2.10.4 Exploration of the Essence of Character Types#
- When storing character types in a computer, you need to find the corresponding code value (integer) of the character.
Storage: character ---> corresponding code value ----> binary --> storage
Reading: binary ----> code value ----> character --> reading - The correspondence between characters and code values is determined by the character encoding table (which is predefined).
- The encoding in Go has been unified to UTF-8, which is very convenient and standardized, eliminating the problem of encoding garbled characters.
2.11 Boolean Types#
2.11.1 Basic Introduction#
- Boolean type is also called bool type; bool type data can only take values true and false.
- The bool type occupies 1 byte.
- The bool type is suitable for logical operations and is generally used for program flow control [Note: this will be detailed later]:
- if conditional control statements;
- for loop control statements.
2.11.2 Example Demonstration#
2.12 String Type#
2.12.1 Basic Introduction#
A string is a sequence of characters of fixed length connected together. Go's strings are made up of single bytes. The bytes of Go's strings use UTF-8 encoding to represent Unicode text.
2.12.2 Example Demonstration#
2.12.3 Notes and Details on Using Strings#
- The bytes of Go's strings use UTF-8 encoding to represent Unicode text, so Golang uniformly uses UTF-8 encoding, and the problem of Chinese garbled characters will no longer trouble programmers.
- Once a string is assigned a value, it cannot be modified: in Go, strings are immutable.
- There are two representations of strings:
(1) Double quotes, which will recognize escape characters.
(2) Backticks, which output the string in its raw form, including newlines and special characters, preventing attacks, outputting source code, etc.
【Example demonstration】
- String concatenation methods
- When a line of string is too long, you can use multi-line strings as follows:
2.13 Default Values of Basic Data Types#
2.13.1 Basic Introduction#
In Go, data types have a default value. When a programmer does not assign a value, the default value is retained. In Go, the default value is also called the zero value.
2.13.2 Default Values of Basic Data Types#
Example:
2.14 Type Conversion of Basic Data Types#
2.14.1 Basic Introduction#
Unlike Java/C, Go requires explicit conversion when assigning values between different types of variables. In other words, data types in Golang cannot be automatically converted.
2.14.2 Basic Syntax#
The expression T(v) converts the value v to type T.
T: is the data type, such as int32, int64, float32, etc.
v: is the variable that needs to be converted.
2.14.3 Example Demonstration#
2.14.4 Notes on Type Conversion of Basic Data Types#
1) In Go, type conversion can be from a smaller range to a larger range, or from a larger range to a smaller range.
2) What is being converted is the data (i.e., value) stored in the variable; the data type of the variable itself does not change!
3) During conversion, for example, converting int64 to int8 [-128 -- 127], the compiler will not report an error at compile time; it will just handle the conversion result as an overflow, which may not be what we expect. Therefore, when converting, you need to consider the range.
2.15 Conversion Between Basic Data Types and STRING#
2.15.1 Basic Introduction#
In program development, we often convert basic data types to strings or convert strings to basic data types.
2.15.2 Converting Basic Types to String#
Method 1: fmt.Sprintf("%parameter", expression) 【This is my personal habit, flexible】
Introduction to the function:
The parameter needs to match the data type of the expression.
fmt.Sprintf() will return the converted string.
Example Demonstration
Method 2: Using functions from the strconv package
Example Explanation
2.15.3 Converting String Types to Basic Data Types#
Use functions from the strconv package
Example Demonstration
Explanation
2.15.4 Notes on Converting String to Basic Data Types#
When converting a String type to a basic data type, ensure that the String type can be converted to valid data. For example, we can convert "123" to an integer, but we cannot convert "hello" to an integer. If we do this, Golang will directly convert it to 0. The same logic applies to other types: float => 0, bool => false.
Example Explanation:
2.16 Pointers#
2.16.1 Basic Introduction#
1) Basic data types store values, also known as value types.
2) To get the address of a variable, use &, for example: var num int, to get the address of num: &num.
Let's analyze the layout of basic data types in memory.
3) Pointer types store an address, and the value stored in the space pointed to by this address is the actual value.
For example: var ptr *int = &num.
Let's illustrate: the layout of pointers in memory.
4) To get the value pointed to by a pointer type, use *, for example: var ptr *int, use *ptr to get the value pointed to by ptr.
2.16.2 Example Demonstration#
1) Write a program to get the address of an int variable num and display it on the terminal.
2) Assign the address of num to the pointer ptr and modify the value of num through ptr.
2.16.3 Details of Using Pointers#
-
Value types all have corresponding pointer types, in the form of *data type. For example, the pointer corresponding to int is *int, and for float32, the corresponding pointer type is *float32, and so on.
-
Value types include: basic data types int series, float series, bool, string, arrays, and structs.
2.17 Value Types and Reference Types#
2.17.1 Explanation of Value Types and Reference Types#
- Value types: basic data types int series, float series, bool, string, arrays, and structs.
- Reference types: pointers, slices, maps, channels, interfaces, etc., are all reference types.
2.17.2 Characteristics of Using Value Types and Reference Types#
1) Value types: variables directly store values, and memory is usually allocated on the stack.
Illustration:
2) Reference types: variables store an address, and the space corresponding to this address actually stores the data (value). Memory is usually allocated on the heap. When no variables reference this address, the data space corresponding to that address becomes garbage, which is collected by the GC.
Illustration:
3) Illustration of the stack and heap memory areas.
2.18 Naming Conventions for Identifiers#
2.18.1 Concept of Identifiers#
1) In Golang, the character sequence used for naming various variables, methods, functions, etc., is called an identifier.
2) Any place where you can name something is called an identifier.
2.18.2 Naming Rules for Identifiers#
1) Composed of 26 uppercase and lowercase English letters, 0-9, and _.
2) Numbers cannot be at the beginning. var num int // ok var 3 num int // error.
3) Golang strictly distinguishes between uppercase and lowercase.
var num int
var Num int
Note: In Golang, num and Num are two different variables.
4) Identifiers cannot contain spaces.
5) The underscore "_" itself is a special identifier in Go, called a blank identifier. It can represent any other identifier, but its corresponding value will be ignored (for example: ignoring a return value). Therefore, it can only be used as a placeholder and cannot be used as an identifier.
6) Cannot use system reserved keywords as identifiers (there are a total of 25), such as break, if, etc.
2.18.3 Examples of Identifiers#
hello // ok
hello 12 // ok
1 hello // error, cannot start with a number
h-b // error, cannot use -
xh // error, cannot contain spaces
h_4 // ok
_ab // ok
int // ok, we ask everyone not to use this
float 32 // ok, we ask everyone not to use this
_ // error
Abc // ok
2.18.4 Notes on Naming Identifiers#
- Package names: Keep the package name consistent with the directory, and try to use meaningful package names that are short and meaningful, avoiding conflicts with standard libraries.
2) Variable names, function names, constant names: Use camel case.
Example:
var stuName string = "tom" Form: xxxYyyyyZzzz...
var goodPrice float32 = 1234.5
- If the first letter of a variable name, function name, or constant name is uppercase, it can be accessed by other packages; if the first letter is lowercase, it can only be used within the same package (Note: it can be simply understood that an uppercase first letter is public, and a lowercase first letter is private). In Golang, there are no public, private, or other keywords.
Example demonstration: