Variables and Assignments
Sample code link: https://repl.it/@jjoco/go-variables-and-assignment
Primitive Types
Like other programming languages, Go has primitive data types:
- Boolean: bool
- String: string
- Signed Integers: int, int8, int16, int32, int64
- Unsigned integers: uint, uint8, uint16, uint32, uint64
- Byte : byte => alias for uint8
- Rune: rune => alias for int32
- Floats: float32, float64
- Complex numbers: complex64, complex128
- Void is not a type
Note: int and uint "are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems"
Regular Assignment
At compile time, the developer can specify the type of the variable declared using the var keyword. As an FYI, Go's variable naming convention is camelCase.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
- Only var is used when creating a new variable
- No colons when specifying a variable's type
- Uninitialized variables are set to their default "zero" value:
- Number types (eg ints, unsigned ints, floats, etc.) are set to 0
- Boolean types are set to
false - String types are set to empty strings
""
Short Assignment
Developers can directly assign a literal to a variable using :=, and the compiler will infer what type of variable it is based on what was assigned.
1 2 3 | |
Multiple Assignments
Similar to other languages, the developer can assign multiple variables at once using regular or short assigning.
1 2 3 4 5 | |
Constants
Constants can be assigned via the const keyword, and camelCase is generally used as the naming convention; PascalCase when exporting a const.
1 2 | |
Operators
Golang supports the same arithmetic, comparison, logical, bitwise, and assignment operators as other C-like languages. They are listed below.
Arithmetic
+Addition-Subtraction*Multiplication/Divison%Modulus++Increment by 1--Decrement by 1
Comparison
<Less than>Greater than<=Less than or equal to>=Greater than or equal to==Equal to!=Not equal to
Logical
&&Conditional AND||Conditional OR!NOT
Assignment
+=add, then assign-=subtract, then assign*=multiply, then assign/=divide, then assign%=modulo, then assign
Bitwise
&Bitwise AND|Bitwise OR^Bitwise XOR<<Left shift>>Right shift