“This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

1 What will you learn in this chapter?

  • What is a variable? Why do we need them?
  • What is a type?
  • How do I create variables?
  • How do I assign a value to a variable?
  • What is a constant? What’s the difference between constants and variables?
  • How do YOU define constants?
  • How do I use constants?

2 Technical concepts covered

  • variable
  • constant
  • type
  • Untyped constant

A variable is a space in memory

A variable is a space in computer memory that can contain a piece of data that can be changed. The word “variable” comes from the Latin “variabilis,” meaning “variable.” In a program, we can create variables to store information for later use.

For example, if we want to keep track of the number of guests in a hotel, “number of guests” would be a variable number. We can create variables to store this information, as shown in the figure below:

4 Where are variables stored?

We discussed ROM, RAM, and auxiliary memory earlier. So where do I store the GO variable? The answer is simple, you don’t have a choice, the compiler will take care of it for you!

5 Variable Identifiers (Variable names)

In most programming languages (and in Go), when we create a variable, we associate it with an identifier. An identifier is the “name” of a variable. An identifier is the “name” of a variable. We use identifiers in our programs to quickly access variables. An identifier consists of letters and numbers. The identifier of a variable is used internally in the program to specify the value stored in it. Identifiers must be short and descriptive.

To create an identifier, the programmer is free to make it explicit. But they must follow these simple rules:

  1. Identifiers can only consist of Unicode characters and numbers, such as: 1,2,3, A, B, B, O…
  2. Identifiers must start with a Unicode character or an underscore “_” and cannot start with a number
  3. Some identifiers cannot be used because they are used as reserved words by the language

    Reserved words in Go are: 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

NumberOfGuests is a valid variable identifier. On the other hand, 113Guests is not valid because it starts with a number. In fact, the naming of variables is also a knowledge, it is very difficult to come up with “see the name, know its meaning” variable identifier.

6 Basic Types

We can store information in variables. But “information” is too broad, and we have to be more precise. Do we need to store numbers (1, 2000, 3), floating point numbers (2.45665), text (” Room 112 non-smoking “)? We need the concept of type to specify what values can be assigned to variables of that type.

The Go language predeclares a set of basic types that you can use immediately in your programs. You can also define your type (we’ll see that later). Now, let’s look at the most common types:

  • string
    • Type name: string
    • Example: “Management office”,” Room 265″,…
  • Unsigned integer
    • Type name: Uint, uint8, uint16, uint32, uint64
    • Example: 2445, 676, 0, 1…
  • The integer
    • Type name: int, int8, int16, int32, int64
    • Example: -1245, 65, 78…
  • Boolean type
    • Type name: bool
    • Example: true, false
  • Floating point Numbers
    • Type name: float32, float64
    • Ex. : 12.67

6.1 About numbers 8, 16, 32 and 64

You may have noticed that we have five types of integers: int, int8, int16, int32, int64. The same is true for unsigned integers, which have uint, uint8, uint16, uint32, and uint64. Floating-point options are more limited: we can use float32 or float64.

If you want to store unsigned numbers, you can use the unsigned integer type. Here are five to choose from:

  • uint8
  • uint16
  • uint32
  • uint64
  • uint

Every one of them, except the last one, has a number attached to it. This number corresponds to the number of bits of memory allocated to store it.

If you’ve read part 1, you know:

  • 8 bit memory, we can store from 0 to 2^{7}+2^{6}+… +2^{0}=2552 decimal number 7 +2 6 +… + 2 0 = 255.
  • Using 16 bits (2 bytes), we can store from 0 to 2^{15}+2^{14}+… + 2 ^ {0} = 65535
  • Using 32 bits (4 bytes), we can store from 0 to 2^{31}+2^{30}+… + 2 ^ {0} = 4294967295
  • Using 64 bits (8 bytes), we can store from 0 to 2^{63}+2^{62}+… + 2 ^ {0} = 18446744073709551615

You will notice that the maximum decimal value of 64 bits is very high. Remember! If you need to store values up to 255, use uint8 instead of uint64. Otherwise, you’ll waste storage space (because you’ll only be using 8 of the 64 bits allocated in memory!).

The last type is uint. If you use this type in your program, the memory allocated for your unsigned integers will be at least 32 bits. The final number of bits will depend on the system on which the program will be running. In a 32-bit system, it is equivalent to the uint32. If the system is 64-bit, the storage capacity of uINT is the same as that of uint64. (To better understand the difference between 32-bit and 64-bit, see the previous chapter.)

7 Variable Declaration

If you want to use a variable in your program, you need to declare it first.

7.1 Three Actions to perform when declaring variables

When you declare a variable, it does:

  1. Bind identifiers to variables
  2. Bind a type to a variable
  3. Initialize the variable value to the default value of the type

When you define a variable and set the type, Go will initialize the value of the variable for you to the type default.

7.2 No initialized variable declaration

In the figure above, you can see how variables are declared. In the first example, we declared a variable of type int named roomNumber. In the second one, we declared two variables on the same line: roomNumber and floorNumber. They are of type int. They have a value of 0 (which is a zero value of type int).

package main

import "fmt"

func main(a) {
    var roomNumber, floorNumber int
    fmt.Println(roomNumber, floorNumber)

    var password string
    fmt.Println(password)
}
Copy the code

Program output:

0 0

Copy the code

The string variable password is initialized with a string zero value, the empty string “”. The roomNumber and floorNumber variables are initialized to a zero of type int, that is, 0.

The first line of the program output is the result of FMT.Println(roomNumber,floorNumber). The second line is the result of fmt.println (password).

7.3 Initializing variable declarations

You can also declare a variable and initialize its value directly. The diagram above depicts the possible syntax. Let’s take an example:

package main

import "fmt"

func main(a) {
    var roomNumber, floorNumber int = 154.3
    fmt.Println(roomNumber, floorNumber)

    var password = "notSecured"
    fmt.Println(password)
}
Copy the code

In the main function, the first statement declares the roomNumber and floorNumber variables. They are int types initialized with the values 154 and 3. The program will then print these variables.

There is an expression or a list of expressions on the left side of the equal sign. We’ll cover expressions in detail in another section.

We then define the variable password, which we initialize with the value “notSecured”. Note that there is no write type, and that Go will give the variable the type of its initialization value. Here the type of “notSecured” is a string; Therefore, the variable password is of type string.

7.4 Shorter variable declarations

The short syntax eliminates the var keyword and the = symbol is replaced with :=. You can also use this syntax to define multiple variables at once:

roomNumber := 154
Copy the code

The type is not explicitly written, and the compiler will infer it from the expression (or list of expressions).

Here’s an example:

package main

import "fmt"

func main(a) {
    roomNumber, floorNumber := 154.3
    fmt.Println(roomNumber, floorNumber)
}
Copy the code

Warning: short variable declarations cannot be used outside functions!

// will not compile
package main

vatRat := 20

func main(a){}Copy the code

Warning: You cannot use the value nil for short variable declarations, and the compiler cannot infer the type of the variable.

8 What is a constant?

Constant comes from the Latin word “constare,” meaning “to stand firm.” A constant is a value in a program that stays the same and does not change during execution. A variable can change at run time; A constant doesn’t change; It will remain the same.

For example, we can store it in a constant:

  • The version of our program. For example, 1.3.2. This value will remain stable while the program is running. We will change this value when we compile another version of the program.
  • The build time of the program.
  • Email template (if our application cannot be configured).
  • An error message was reported.

In general, use constant storage when you are sure that you will never need to change a value during program execution. Constants are immutable. Constants come in two forms: typed and untyped.

9 has type constants

This is a typed constant:

const version string = 1.3.2 ""
Copy the code

The const keyword indicates to the compiler that we will define oneoftenThe amount. After the const keyword, the identifier of the constant is set. In the example above, the identifier is “version”. The type is clearly defined (here it isstring) and the value of the constant (as an expression).

10 Untyped constants

This is an untyped constant:

const version = 1.3.2 ""
Copy the code

An untyped constant:

  • There is no type
  • There is a default value
  • There is no limit to

10.1 An Untyped Constant has no type…

An example to illustrate the first point (untyped constants have no type)

package main

import "fmt"

func main(a) {
    const occupancyLimit = 12

    var occupancyLimit1 uint8
    var occupancyLimit2 int64
    var occupancyLimit3 float32

    // assign our untyped const to an uint8 variable
    occupancyLimit1 = occupancyLimit
    // assign our untyped const to an int64 variable
    occupancyLimit2 = occupancyLimit
    // assign our untyped const to an float32 variable
    occupancyLimit3 = occupancyLimit

    fmt.Println(occupancyLimit1, occupancyLimit2, occupancyLimit3)
}
Copy the code

Program output:

12 12 12
Copy the code

In this program, we first define a typeless constant called occupancyLimit with a value of 12. Here, the constant has no specific type, but is set to an integer value.

Then we define 3 variables: occupancyLimit1, occupancyLimit2 and occupancyLimit2 (the types of these variables are Uint8, Int64 and Float32).

We then assign the value of occupancyLimit to these variables. Our program is compiled to show that the value of our constant can be put into different types of variables!

If you change the value of occupancyLimit to 256, the compilation will report an error. Think about why?

10.2… But there are default types when necessary

To understand the concept of default types, let’s take another example

package main

import "fmt"

func main(a) {
    const occupancyLimit = 12

    var occupancyLimit4 string

    occupancyLimit4 = occupancyLimit

    fmt.Println(occupancyLimit4)
}
Copy the code

In this program, we define a constant occupancyLimit that has a value of 12 (an integer). We define a variable of type occupancyLimit4 as a string. We then try to assign the value of the constant to occupancyLimit4. We’re trying to convert integers to strings. Does this program compile? The answer is no! The compiler error is:

./main.go:10:19: cannot use occupancyLimit (type int) as type string in assignment
Copy the code

An untyped constant has a default type defined by the value assigned to it at compile time. In our example, the default type of occupancyLimit is int. You cannot assign an int to a string variable.

The default type of an untyped constant is:

  • Bool (Boolean)
  • rune
  • Int (integer value)
  • Float64 (Float value)
  • Complex128
  • String (string value)
package main

func main(a) {

    // default type is bool
    const isOpen = true
    // default type is rune (alias for int32)
    const MyRune = 'r'
    // default type is int
    const occupancyLimit = 12
    // default type is float64
    const vatRate = 29.87
    // default type is complex128
    const complexNumber = 1 + 2i
    // default type is string
    const hotelName = "Gopher Hotel"} # # #10.3There is no restriction on untyped constants. Untyped constants have no type or default type when needed. The value of an untyped constant may overflow its default type. Such constants have no type; Therefore, it does not depend on any type restrictions. Let's take an example:` ``Go package main func main() { // maximum value of an int is 9223372036854775807 // 9223372036854775808 (max + 1 ) overflows int const profit = 9223372036854775808 // the program compiles }Copy the code

In this program, we’ve created an untyped constant called profit whose value is profit and whose value is 9223372036854775808, This value exceeds the maximum allowed int (int64 on 64-bit machines) : 9223372036854775807. This program compiles perfectly. But when we try to assign this constant value to a typed variable, the program will fail to compile. Let’s take an example to prove it:

package main

import "fmt"

func main(a) {
    // maximum value of an int is 9223372036854775807
    // 9223372036854775808 (max + 1 ) overflows int
    const profit = 9223372036854775808
    var profit2 int64 = profit
    fmt.Println(profit2)
}
Copy the code

This program defines a variable profit2 of type INT64. We then try to assign the value of the untyped constant profit to profit2.

Let’s try the compiler:

$ go build main.go
# command-line-arguments
./main.go:9:7: constant 9223372036854775808 overflows int64
Copy the code

We get a compilation error, which is good. What we’re trying to do is illegal.

10.4 Why Use Constants

  1. Can improve the readability of your program

If chosen properly, constant identifiers give the reader more information than the original value for comparison:

loc, err := time.LoadLocation(UKTimezoneName)
iferr ! =nil {
  return nil, err
}
Copy the code
loc, err := time.LoadLocation("Europe/London")
iferr ! =nil {
  return nil, err
}
Copy the code

We use the constant UKTimezoneName instead of the original value “Europe/London”. We hide the complexity of time zone strings from the reader. In addition, the reader will understand our intention: we want to load the UK location.

  1. You provide the potential to pay the value (by another program or in your program)
  2. The compiler may improve the generated machine code. You say to the compiler that this value will never change; If the compiler is smart (and it is), it will use it smartly.

11 Select identifiers (variable names, constant names)

Naming variables and constants is not an easy task. When you choose a name, you must ensure that the selected name provides the correct amount of information about its name. If you choose a good identifier name, other developers working on the same project will be grateful because it will be easier to read the code. When we say “send the right message,” the word “right” is ambiguous. There are no scientific rules for naming program structures. Even without scientific rules, I can give you some advice that our community shares.

  1. Avoid one-letter naming: it conveys too little information about what is stored. The exception is that counters are usually named K, I, and j (inside the loop, which we’ll cover later)

  2. Use hump naming: This is a well-established convention in the Go community. OccupancyLimit is better than Occupancy_Limit and occupation-Limit.

  3. Not more than two words profitValue is very good, profitValueBeforeTaxMinusOperationalCosts would be too long

  4. Avoid mentioning type descriptionString in the name. Description is better. Go is already statically typed; You don’t need to provide the reader with type information.

12 Practical Application

12.1 the task

12.1.1 programming

Write a program that does the following:

  • Create a file namedhotelNameAnd the value of"Gopher Hotel"String constant of
  • Create two untyped constants containing 24.806078 and -78.243027 respectively. The names of the two constants arelongitudelatitude. (Somewhere in the Bahamas)
  • Create a file namedoccupancyintType variable with an initial value of 12.
  • printhotelName,longitude,latitudeAnd print in a new lineoccupancy.

12.1.2 Questions and Answers for prizes

  1. longitudelatitudeWhat is the default type of?
  2. latitudeWhat is the type of?
  3. variableoccupancyintType, is it a 64-bit, 32-bit, or 8-bit integer?

12.2 Reference Answer

12.2.1 programming

package main

import "fmt"

func main(a) {
    const hotelName string = "Gopher Hotel"
    const longitude = 24.806078
    const latitude = 78.243027
    var occupancy int = 12
    fmt.Println(hotelName, longitude, latitude)
    fmt.Println(occupancy)
}
Copy the code

We start with the definition of the type constant hotelName and the definitions of Longitude and latitude (untyped). Then we define occupancy variable (type: int) and set it to 12. Note that an alternative syntax is also possible:

  • Short variable declarations
occupancy := 12
Copy the code
  • Types can be omitted from standard declarations
var occupancy = 12
Copy the code
  • We can declare and assign variables in two steps
var occupancy int
occupancy = 12
Copy the code

12.2.2 Prize answers

  1. longitudelatitudeWhat is the default type of? float64
  2. latitudeWhat is the type of? No type,latitudeSame thing (they’re all untyped constants)
  3. variableoccupancyintType, is it a 64-bit, 32-bit, or 8-bit integer? Depends on the compiled computer.intIs an implementation-specific size type on 32-bit computers, which will be a 32-bit integer (int32); On 64-bit computers, it will be a 64-bit integer (int64).

13 test in class

13.1 the problem

  1. What is an identifier?
  2. What type of character should an identifier start with?
  3. What is the type of the variable?
  4. What is a byte?
  5. When you declare a variable of type bool, what is its value (after initialization)?
  6. What are the three main characteristics of untyped constants?

13.2 the answer

  1. What is an identifier? An identifier is a group of letters and numbers used to access variables in a program.
  2. What type of character should an identifier start with? Start with a letter or underscore
  3. What is the type of the variable? The type of a variable is the set of allowed variable values
  4. What is a byte? A byte consists of eight binary digits
  5. When you declare a variable of type bool, what is its value (after initialization)? False, when you declare a variable, it is initialized to the default value of its type (zero).
  6. What are the three main characteristics of untyped constants?
    • No type
    • There’s a default type
    • Unlimited (e.g., can overflow the maximum integer value)

14 Key Points

  • The name of a variable or constant is called an identifier.
  • Identifiers are usually written in a hump
  • Variables and constants allow you to store a value in memory
  • Constants are immutable, which means we cannot change their values during program execution
  • Variables have a type that defines the set of values they can hold
  • When you create a variable, its value is initialized to zero of its type
    • This is important
    • It can be a source of error
    • There are no uninitialized variables in Go
  • There are two types of constants in Go
    • Typed constant
    • Untyped constants have no type, only one default type, and can overflow their default type