1. Constants
- Data types in constants can only be Boolean, numeric (integer, float, and plural) and string
- Definition Format: const identifier [Type] = value, [type] can be omitted, the compiler infers its type based on the value of the variable
- Defining types
- Explicit type definition: const a string = "BAC"
- Implicit type definition: const B = "ABC"
- Constants can be used with Len (), Cap (), unsafe. The Sizeof () function evaluates the value of an expression. In a constant expression, the function must be a built-in function, otherwise the compilation
- A = "Hello" unsafe. Sizeof (a): The string type is a structure in go, containing pointers and lengths to the underlying array, each of which is 8 bytes, so the string type size is 16 bytes.
2. Variables
- When variables are initialized, the type of the variable is ignored and the system is automatically inferred, so we can remove the var keyword and simplify it to a:=69, but it is important to note that this declaration method can only be used in the body of the function, not in the Declaration and assignment of global variables;
- A: = 30, cannot be used to assign values to an already existing variable
- Local variables must be used once they are declared, or compile errors will be reported
- Used before a variable is defined, and a compilation error is reported
- A, B, c: = 5, 7, "ABC": Parallel or simultaneous assignment, can also be used when a function returns multiple return values: val, err = Func1 (parameter)
- Exchange values for two variables: A, B = B, a two variables must be of the same type
- The blank identifier "_" is used to discard values, for example: 5 is discarded in _,b = 5,7; In fact "_" is a write-only variable and cannot get its value; This is done because you have to use all the declared variables in the go language, but sometimes you don't need to use the return value from a function, for example: ret1,_ = FUNC2 (parameter), the second return value we do not need to declare it and assign a value
Go language learning-constants and variables