Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

 Golang - Variables and Constants

5. Variables and Constants

Variables:

Variables are used to store data values that can be changed or manipulated during the program's execution. In Go, you declare a variable using the 'var' keyword followed by the variable name, its type, and optionally an initial value.

var age int            // Declare a variable named "age" of type int.
age = 25 // Assign a value to the "age" variable.
 

Alternatively, you can use the short declaration syntax ':=' to declare and initialize a variable. Go will automatically infer the variable's type.

name := "Alice"      // Declare and initialize a variable named "name".

 

Variable Types:

Go has various built-in data types for variables, including:

  • Numeric Types:int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, complex64, complex12
  • String Type: string
  • Boolean Type: bool
  • Character Type: byte (an alias for uint8) and rune (represents a Unicode code point)
  • Pointers: *int, *string, etc.

1. Numeric Types

1. int:

The 'int' type represents signed integers. Its size depends on the platform, commonly being either 32 or 64 bits.

Example:
var age int = 30

 

2. int8, int16, int32, int64:

These are specific-sized signed integer types, with sizes of 8, 16, 32, and 64 bits respectively.

Example:
var temperature int32 = 25

 

3. uint:

The 'unit'type represents unsigned integers (non-negative integers). Like 'int', its size depends on the platform.

Example:
var count uint = 100

 

4. uint8, uint16, uint32, uint64:

Similar to their signed counterparts, these types are unsigned integers with specific bit sizes.

Example:
var quantity uint16 = 500

 

5. float32, float64:

Floating-point types represent decimal numbers with single (32-bit) or double (64-bit) precision.

Example:
var pi float64 = 3.14159

 

6. complex64, complex128:

Complex number types consist of real and imaginary parts. 'complex64'uses 32-bit float parts, while 'complex128' uses 64-bit float parts.

Example:
var z complex128 = 2 + 3i

 

2. String Type

The  'string'  type represents a sequence of characters. Strings are used to store textual data, such as words, sentences, or even binary data in some cases. Strings in Go are immutable, meaning that once created, their contents cannot be changed.
 

1. String Declaration:

You can declare a string variable by using the 'string' type and assigning a value to it.

var message string = "Hello, Go!"

 

2. String Literals:

Strings are created using string literals. A string literal is a sequence of characters enclosed in double quotes '"..."'.

greeting := "Welcome to Go!"

 

3. String Concatenation:

You can concatenate strings using the '+' operator.

firstName := "John"
lastName := "Doe"
fullName := firstName + " " + lastName

 

 4. String Length:

To get the length (number of characters) of a string, you can use the built-in 'len' function.

text := "Hello, world!"
length := len(text) // length will be 13

 

5. String Indexing:

Strings in Go are indexed starting from 0. You can access individual characters using square brackets '[]'.

word := "Go"
firstLetter := word[0] // firstLetter will be 'G'

 

6. Unicode Support:

Go's string type supports Unicode characters, which means you can work with strings containing characters from various languages and scripts.

unicodeString := "こんにちは"      // Japanese greeting "Konnichiwa"

 

7. String Escapes:

Strings can contain escape sequences to represent special characters like newline ('\n'), tab ('\t'), and others.

escapedString := "First Line\nSecond Line"

 

8. Raw String Literals:

Raw string literals, indicated by backticks ```, allow you to include special characters without escaping.

rawString := `This is a raw string literal.
It can span multiple lines without escapes.`

 

9. String Slicing:

You can extract substrings from a string using slicing.

message := "Hello, World!"
substring := message[7:12] // "World"

 

10. String Functions:

Go's 'strings' package provides various functions for working with strings, such as 'strings.HasPrefix', 'strings.HasSuffix', 'strings.Contains', 'strings.ToUpper', 'strings.ToLower', and more.

import "strings"

text := "Hello, Go!"
containsGo := strings.Contains(text, "Go") // true
uppercase := strings.ToUpper(text) // "HELLO, GO!"

 

Strings are fundamental to working with textual data in programming. Understanding how to declare, manipulate, and process strings is essential for building effective applications that involve user input, text processing, and more.

3. Boolean Type

The 'bool' type represents a binary value that can be either 'true' or  'false'. Booleans are used to make logical decisions in your code, control the flow of execution, and perform comparisons.

1. Boolean Declaration:

You can declare a boolean variable by using the 'bool' type and assigning a value to it.

var isRaining bool = true

 

2. Boolean Literals:

Boolean literals have only two possible values: 'true' and 'false'.

isSunny := false

 

3. Comparison Operators:

Comparison operators are used to compare values and return boolean results.

temperature := 25
isHot := temperature > 30 // isHot will be false
isWarm := temperature >= 20 // isWarm will be true
isCold := temperature < 18 // isCold will be false
isModerate := temperature == 25 // isModerate will be true

 

4. Logical Operators:

Logical operators combine boolean values and return boolean results.

  • '&&'(AND): Returns 'true' if both operands are'true'.
  • '||' (OR): Returns 'true' if at least one operand is'true'.
  • ' ! ' (NOT): Negates the value of a boolean expression.
isWeekend := true
isSunny := false
isGoodWeather := isWeekend && isSunny // isGoodWeather will be false

 

5. Conditional Statements:

Booleans are commonly used in conditional statements to control the flow of a program.

if isSunny {
fmt.Println("It's a sunny day!")
} else {
fmt.Println("It's not sunny.")
}

 

6. Boolean Functions:

Functions often return boolean values, indicating the success or failure of an operation.

func isEven(number int) bool {
return number%2 == 0
}

 

7. Boolean Constants:

Go has two pre-declared boolean constants: 'true' and  'false'.

isTrue := true
isFalse := false

 

8. Conditional Expressions:

You can use boolean expressions within various statements and constructs.

result := 0
if isWeekend && isSunny {
result = 1
} else {
result = 2
}

 

Booleans are vital for decision-making and controlling the execution of your code. By understanding boolean operations and how to use them effectively, you can build logic-driven applications that respond to various conditions and requirements.

4. Character Type:

C++ or Java). Instead, characters are represented as Unicode code points using the 'rune'  type, which is an alias for 'int32'.

1. Unicode and Runes:

Unicode is a character encoding standard that assigns unique codes to almost every character in all known scripts and languages. In Go, a 'rune' represents a Unicode code point.

2. Declaring and Using Runes:

You can declare a 'rune' using single quotes '''' and assign it to a variable of type 'rune' .

var letter rune = 'A'

 

You can use 'rune' literals to directly represent Unicode code points.

heart := '❤'

 

3. Iterating Over a String as Runes:

Strings in Go are UTF-8 encoded sequences of bytes, not characters. To iterate over a string's characters as 'rune' s, you can convert the string to a slice of runes.

text := "こんにちは" // "Hello" in Japanese
runes := []rune(text)
for _, r := range runes {
fmt.Printf("%c ", r)
}

// Output: こ ん に ち は

 

4. String Length vs. Rune Count:

The 'len'  function returns the number of bytes in a string, not the number of runes.

text := "こんにちは"
length := len(text) // length will be 15 (bytes)

 

For counting runes, you need to convert the string to a slice of runes first.

runes := []rune(text)
runeCount := len(runes) // runeCount will be 5 (runes)

 

5. Handling Unicode Characters:

Since Go uses Unicode for strings, you can work with characters from various languages and scripts seamlessly.

emoji := '😃'
fmt.Printf("Unicode code point: %U\n", emoji)

// Output: Unicode code point: U+1F603

 

The 'fmt.Printf("%"U)'format specifier is used to print the Unicode code point of a 'rune'.

In summary, Go uses the 'rune' type to represent characters as Unicode code points. This approach allows Go to handle characters from all languages and scripts in a unified manner. When working with strings containing characters outside the ASCII range, it's essential to understand how runes are used and how to iterate through them to ensure correct handling of characters.

5. Pointers

A pointer is a variable that stores the memory address of another variable. In simpler terms, it points to the location in memory where a value is stored rather than holding the actual value itself.

1. Declaring Pointers:

You can declare a pointer by using the '*' symbol followed by the variable type. For example, if you have an 'int' variable, you can declare a pointer to it using '*int'.

var x int = 42
var ptr *int
ptr = &x // Assign the memory address of x to ptr

 

In this example, 'ptr' is a pointer to an integer. The '&'symbol is used to get the memory address of the variable 'x'.

2. Dereferencing Pointers:

Dereferencing a pointer means accessing the value stored at the memory address it points to. You use the '*' symbol again to dereference a pointer.

var y int
y = *ptr // Assign the value pointed to by ptr to y

 

In this example, '*ptr' gives you the value stored at the memory address pointed to by 'ptr', and this value is assigned to 'y'.

3. The Zero Value of Pointers:

If a pointer is declared but not assigned a memory address, it holds a special value called the "zero value" for pointers, which is 'nil'.

var ptr *int          // ptr is nil

 

4. Pointer Arithmetic:

Go doesn't support pointer arithmetic like some other languages do. You can't directly perform arithmetic operations on pointers.

5. Passing Pointers to Functions:

Passing a pointer to a function allows the function to modify the original value the pointer points to. This is especially useful when you want to avoid copying large data structures.

func incrementByPointer(val *int) {
*val++
}

func main() {
x := 10
ptr := &x
incrementByPointer(ptr)
fmt.Println(x) // Output: 11
}

 

In this example, the 'incrementByPointer' function takes a pointer as an argument and increments the value it points to.

6. Using Pointers vs. Values:

Using pointers can be more memory-efficient, especially when working with large data structures. However, excessive use of pointers can make the code harder to read and understand.

7. Pointers to Structs:

Pointers are often used to work with struct values, as structs can be relatively large and copying them frequently might be inefficient.

type Person struct {
Name string
Age int
}

func main() {
person := Person{Name: "Alice", Age: 25}
personPtr := &person
fmt.Println(personPtr.Name) // Access field using pointer
}

 

Pointers are a powerful tool for managing memory and sharing data between different parts of a program. Understanding how pointers work can help you write more efficient and flexible code, especially when dealing with large data or when you need to modify variables in functions. However, it's important to use pointers judiciously to avoid introducing unnecessary complexity.

Constants:

Constants are identifiers that represent fixed, unchangeable values. They are useful for defining values that should remain constant throughout the program's execution.

Constant Declaration:

const pi = 3.14159         // Declare a constant named "pi" with the value 3.14159.

 

The 'const' keyword is used to declare a constant, followed by the constant name and its value.

1. Enumerated Constants:

const (
Monday = iota // 0
Tuesday // 1
Wednesday // 2
Thursday // 3
Friday // 4
Saturday // 5
Sunday // 6
)

 

The 'iota' identifier is used to create a sequence of related constants that increment automatically.

2. Typed Constants:

type Currency int

const (
USD Currency = iota // 0
EUR // 1
GBP // 2
JPY // 3
)

 

Typed constants are associated with a specific type, making them more expressive and restrictive.

Advantages of Constants:

  • Constants provide better clarity and meaning to the values used in your code.
  • They prevent accidental changes to important values.
  • Constants can be used in situations where a value needs to be consistent across multiple parts of your code.

Both variables and constants play crucial roles in writing effective Go programs. By understanding their differences and when to use each, you'll be able to create more reliable and maintainable code.