Before we begin, let's think about something that often happens in our daily lives. Does your mom always say, “Put stationery like scissors and glue in the first drawer, and put toys in the second drawer?” Why does she always say that? If you put a pencil in the first drawer today and move it to the second drawer the next day, you would have to go through the trouble of opening all the drawers to find the pencil every time (something that happens every day in my house...). So, if you make a promise to put certain item in certain drawer, even if my mother tries to find something while I am out for a while, she can easily know where it is. If mom also puts it back in its place after use, there will be no problem for you to find it later.
Also, think about the moment the package is delivered to your home. You must enter your address to receive delivery. It will be delivered exactly to this address. If you enter an incorrect address, your package will be delivered to someone you don't know.
Similarly, in computer programs, to store a value in the exact location you want it to be stored, you must name a specific storage space and insert or change the value at that location. These stores are called variables or constants, and this chapter discusses how to use variables or constants.
1. Variables
If you create a box that can hold a specific value and put a 'variable item' into it as desired, it is called a variable. Variable is declared using Golang's keyword var
package main
import "fmt"
function main() {
var a int
var pi float32 = 3.14
fmt.Println(a, pi)
a = 10
pi =3.1415
fmt.Println(a, pi)
var b, c int = 1, 2
fmt.Println(b, c)
var d = true
fmt.Println(d)
f := “Hello”
fmt.Println(f)
}
$ go run variables.go
0 3.14
10 3.1415
1 2
true
Hello
- 07: Write the variable name and variable type after the var keyword. Golang supports the following variable types.
Data Type | Data Range | Description |
uint8 | 0 ~ 255 | unsigned 8 bits integer |
uint16 | 0 ~ 65,535 | unsigned 16 bits integer |
unit32 | 0 ~ 4,294,967,295 | unsigned 32 bits integer |
uint64 | 0 ~ 18,446,744,073,709,551,615 | unsigned 64 bits integer |
uint | uint32 on 32-bit systems, uint64 on 64-bit systems | |
int8 | -128 ~ 127 | signed 8 bits integer |
int16 | -32,768 ~ 32,767 | signed 16 bits integer |
int32 | -2,147,483,648 ~ 2,147,483,647 | signed 32 bits integer |
int64 | -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
signed 64 bits integer |
int | int32 on 32-bit systems, int64 on 64-bit systems | |
float32 | IEEE-754 32 bits floating point, 7 digits precision | |
float64 | IEEE-754 64 bits floating point, 12 digits precision | |
complex64 | Complex number consisting of real and imaginary parts of size float32 | |
complex128 | Complex number consisting of real and imaginary parts of size float64 | |
uintptr | A pointer type with the same size as uint. | |
bool | 8-bit data type to represent True and False | |
byte | 8-bit data type | |
rune | Data type for Unicode storage, size is the same as int32 | |
string | Data type for storing strings |
Data Type?
Data types are an essential concept in computer programming and data management. They serve several important purposes:
ᆞData Storage: Data types define how data is stored in memory. Different data types require varying amounts of memory to store their values. For example, an integer typically requires less memory than a floating-point number with the same value.
ᆞData Integrity: Data types help ensure data integrity by defining what kind of data can be stored in a variable or data structure. This prevents unintended data corruption or misuse. For instance, if you declare a variable as an integer, you can't accidentally assign it a string value.
ᆞOperations: Different data types support different operations. For example, you can perform mathematical operations on numerical data types like integers and floating-point numbers, but not on strings or boolean values. Data types determine what operations are valid and what results you can expect.
ᆞMemory Efficiency: Choosing the appropriate data type can lead to more memory-efficient programs. Using a data type with a smaller memory footprint when a larger one isn't necessary can save memory and improve program performance.
ᆞCode Clarity: Data types make code more readable and self-explanatory. When you declare a variable with a specific data type, it's easier for other developers (or your future self) to understand how that variable should be used and what kind of data it will hold.
ᆞError Handling: Data types help catch errors early in the development process. If you attempt an operation that's not supported by a particular data type, the compiler or interpreter will often generate an error, which can be addressed before the program runs.
ᆞOptimization: Some programming languages can optimize code better when they know the data types involved. For example, a compiler might generate more efficient machine code for a specific data type, leading to faster execution.
ᆞInteroperability: When working with multiple programming languages or data sources, data types help ensure that data can be transferred and processed correctly. Different languages and systems may have their own data type representations, and data type conversions help bridge these gaps.
Why are there different types of int?
In the past, memory prices were quite expensive, so there was a need to manage data efficiently. For example, if you have an int variable storing test scores, you typically only store values from 0 to 100 (int8 or uint8 will suffice), so you don't need to allocate twice as much storage as int16.
When first specifying a variable, it is important to estimate how much storage it will use and specify the appropriate type.
Signed vs Unsigned?
Numeric types can be expressed in ‘signed’ and ‘unsigned’ formats. “Unsigned” means that it is a data format that cannot store negative numbers (data with ‘-’ in the sign), and can store values up to twice as large as the ‘signed’ format (since positive numbers can be stored as much as negative numbers). there is.
The numeric data type basically has positive (‘+’ value) and negative (‘-‘ value) values, and the notation ‘signed’ is not indicated separately as the default value.
- 08: You can also assign an initial value to a variable declaration. An initial value of 3.14 is assigned to the float32 type variable pi. If an initial value such as line 06 is not specified, it is initialized to Zero Value (0 for numbers, false for bool, and empty string for strings).
- 11~12: You can assign a declared variable a value that matches the variable type. Here, the '=' symbol is called an assignment operator, and its function is to insert the value calculated on the right into the left.
- 15: You can declare multiple variables of same type at once.
- 18: If Go doesn't specify a variable type, it automatically infers the data type by inferring its initialized value
- 21: The ‘:=’ syntax can declare and initialize variables at the same time. In the case of this line, the syntax is the same as var f string = "Hello". However, this syntax can only be used within a function.
2. Naming Rule
Just as in real life you avoid names that are difficult to pronounce or use slang, there are some rules when naming variables in Go.
- Variable names can only use characters, _ , and numbers
- The first letter of the variable name must start with a letter or _
- Reserved words cannot be used as variable names. The following are reserved words in Go
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
3. Constants
Unlike variables, constants are values that cannot be changed once assigned. The declaration method is similar to variables, but uses const instead of var. The reasons for using constants are:
- Value Preservation: Constants hold values that should not change during the execution of a program. This is crucial for preserving data integrity and ensuring that critical values remain constant throughout the program's execution
- Readability and Maintainability: Using constants instead of "magic numbers" (hard-coded numerical values) in your code makes it more readable and maintainable. Constants provide meaningful names for values, making it easier for other developers (including yourself) to understand the code's purpose.
- Avoiding Errors: Constants prevent accidental modification of important values. When a value is declared as a constant, the compiler or interpreter will generate an error if you attempt to change it. This helps catch bugs early in the development process.
- Flexibility: Constants can be easily changed in one place if a value needs to be updated throughout the codebase. This allows for quick and consistent changes to program behavior.
- Portability: Constants can make code more portable between different systems and environments. By defining constants for values like file paths or system parameters, you can adapt your program to different configurations by changing the constants rather than rewriting the entire code.
- Documentation: Constants serve as a form of self-documentation. When you give a constant a meaningful name (e.g., PI for the mathematical constant pi), it provides information about the purpose and usage of that value without requiring additional comments.
package main
import "fmt"
func main() {
const PI float32 = 3.14
fmt.Println(PI)
// PI = 3.141592
const (
ENG = "English"
MAT = "Math"
SCI = "Science"
)
fmt.Println(ENG, MAT, SCI)
const (
GREEN = iota
YELLOW
RED
)
fmt.Println(GREEN, YELLOW, RED)
}
$ go run constants.go
3.14
English Math Science
0 1 2
- 07: Declare a float32 type constant called PI with an initial value of 3.14.
- 09: If you remove the '//' symbol and run it, you get the error below. As mentioned, once a constant is declared, it cannot be assigned a new value.
$ go run constants.go
# command-line-arguments .\constants.go:9:2: cannot assign to PI (neither addressable nor a map index expression)
Comment
When coding a program, there are times when you want to include a description, regardless of the code. In Go, if there is a '//' mark on a line, the content from that mark to the end of the line is treated as a comment and is not executed. To add comments to multiple lines, use the '/*' and '*/' pairs.
- 11~15: You can declare several constants with similar properties at once. In this case, use ‘(‘ and ‘)’
- 19~23: To assign constant values sequentially starting from 0, you can use an identifier called iota. In this case, GREEN with iota specified is assigned 0, and the remaining constants are given values that increase by 1 in that order
'Programming > Easy Go' 카테고리의 다른 글
Using Conditional Statements: if / switch (0) | 2025.01.09 |
---|---|
Operators(Arithmetic, Comparison, Logical) (2) | 2024.02.07 |
Print to Screen (1) | 2024.02.07 |
Setup Go development environments (0) | 2023.09.06 |
About Go Language (0) | 2023.09.06 |