Hello my friend,
We continue our blog series about learning Go (Golang) as second programming language, which you can use for network and IT infrastructure automation. Today we’ll talk about the basic data types and variables both in Python and Go
How To Start Automating?
Any programming language, whether it is Python or Go (Golang), is a tool to implement your business logic. Whilst it is very important to be experienced with the tool, it is important also to understand the wide context of network automation, and this is where our trainings will kick start you:
We offer the following training programs in network automation for you:
- Zero-to-Hero Network Automation Training
- High-scale automation with Nornir
- Ansible Automation Orchestration with Ansble Tower / AWX
- Expert-level training: Closed-loop Automation and Next-generation Monitoring
During these trainings you will learn the following topics:
- Success and failure strategies to build the automation tools.
- Principles of software developments and the most useful and convenient tools.
- Data encoding (free-text, XML, JSON, YAML, Protobuf).
- Model-driven network automation with YANG, NETCONF, RESTCONF, GNMI.
- Full configuration templating with Jinja2 based on the source of truth (NetBox).
- Best programming languages (Python, Bash) for developing automation
- The most rock-solid and functional tools for configuration management (Ansible) and Python-based automation frameworks (Nornir).
- Network automation infrastructure (Linux, Linux networking, KVM, Docker).
- Orchestration of automation workflows with AWX and its integration with NetBox, GitHub, as well as custom execution environments for better scalability.
- Collection network data via SNMP and streaming telemetry with Prometheus
- Building API gateways with Python leveraging Fast API
- Integration of alerting with Slack and your own APIs
- … and many more
Moreover, we put all mentions technologies in the context of real use cases, which our team has solved and are solving in various projects in the service providers, enterprise and data centre networks and systems across the Europe and USA. That gives you opportunity to ask questions to understand the solutions in-depth and have discussions about your own projects. And on top of that, each technology is provided with online demos and labs to master your skills thoroughly. Such a mixture creates a unique learning environment, which all students value so much. Join us and unleash your potential.
What Are We Going To Talk Today About?
Once you know how to write your first “Hello, World” application, the next step is to start exploring how to add a little bit more dynamics with variables, as variables are storage containers for data of various types That’s exactly what we are going to discuss today:
- What are the most simplistic data types you have in programming language in general and in Python and Go in particular?
- How to store your data in variables?
Explanation
Data Types
Ultimately, computers deal with bits that are sequences of zeroes and ones, e.g., 01110, at least until quantum computers are introduced. At the same time, for us, humans is way easier to deal with complex information, so deal with numbers, texts (composed of punctuation and words), images, and many other data types. To be represented on computers, this data is to be encoded in binary format, which is those sequences of ones and zeroes. To scratch the surface, in this blog post we are talking about the most fundamental data types, which are used to compose other, more complicated data types:
Data Type | Sub type | Explanation | Example |
---|---|---|---|
numeric | signed integer (int) | General purpose whole number (without any fraction) | 0, 14, -15 |
unsigned integer (uint) | General purpose whole number, which cannot be negative | 0, 14 | |
float | General purpose number with fraction part | 0.0, -12.2131, 12.3242 | |
Textual | character | Single character (can be ascii, utf-8, etc encoding) | ‘a’, ‘F’, ‘1’ |
string | Zero or more characters together | ”, ‘asd sdfds’ | |
Boolean | bool | closest to zeros and ones. Element of logic, which suggests if value is true or false | true, false |
Variables
Although you can use values with variables directly in your code, it is typically impractical as you may need to use the value multiple times. Also, it is often that various values are to be provided by users in various input forms (which will be covered later in blogs). This is where variables come to the stage. Variables are storage containers for your data, which name you use through the code. Again, risking to oversimplify matters, there are two types of variables:
Variable Type | Explanation |
---|---|
Value | The most common variable type, which exists in all the programming languages. It creates a storage container for the variable |
Pointer | More advanced concept, which exists in some programming languages (e.g., it exists in Go / Golang and C, but doesn’t exist in Python). It creates storage container for memory address, which points to RAM location, where actual variable is stored. |
Let’s bring these things together to see how it works together.
Examples
For both programming language in our blog series (Go / Golang and Python), we are going to implement the following scenario:
- Create variables of different data types:
- String variables for username and ip address of the device you are to connect
- Unsigned integer variable for storing number of attempts to connect
- Boolean variable to store flag if you are willing to reconnect on unsuccessful attempt or not
- Print all those variables together in one string to stdout (console).
Python
Here is the code example for Python:
1
2
3
4
5
6
7
8
9
10 """From Python to Go: Python: 002 - Basic data types and variables"""
# Variables block
username = "admin"
ip_address = "10.10.10.10"
reconnect_attempts = 3
is_reconnecting = True
# Printing block
print(f"You are connecting to {ip_address} with username {username}, with reconnecting set to {is_reconnecting} and {reconnect_attempts} attempts.")
Some explanation:
- Assignment of variable in Python is done using the following syntax:
1variable_name = variable_value
- Python is dynamic typing programming language, which means Python itself determines the most appropriate data type for the variable and act accordingly.
- For printing output the concept of f-string (stands for formatted string) was used, where you create a string using built-in templating functionality of Python.
Let’s run the code:
1
2 $ python3.10 main.py
You are connecting to 10.10.10.10 with username admin, with reconnecting set to True and 3 attempts.
Although it may seem extremely easy, it is important to get foundation right. In our zero-to-hero network automation training and other training programs we build solid foundation with you and for you.
Go (Golang)
Without Pointers
With Inferring Data Types
First of all, let’s write the code for exactly the same example as we’ve just done for Python:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package main
import (
"fmt"
)
func main() {
// Variables block
username := "admin"
ipAddress := "10.10.10.10"
reconnectingAttempts := uint(3)
isReconnecting := true
// Printing block
fmt.Printf(
"You are connecting to %v with username %v, with reconnecting set to %v and %v attempts.\n",
ipAddress,
username,
isReconnecting,
reconnectingAttempts,
)
}
Some explanation for the code above:
- Variables in Go can be assigned in multiple ways, but the most popular format is:
1variableName := variableValue
- Naming conventions for Go is to use camel case (or, shall I say camelCase).
- Go is static typing language; however, to simplify life of developers coming from Python or other dynamic programming language to a degree it tries to infer data type.
- You can cast explicit data type by using the corresponding function, for example we used function uint() to signal that 3 is actually an unsigned integer, rather than a signed integer, what is inferred by default.
Let’s execute this Go / Golang code:
1
2 $ go run .
You are connecting to 10.10.10.10 with username admin, with reconnecting set to true and 3 attempts.
With Static Data Types
The syntax above is very user friendly and I recommend to use it, whenever you write Go / Golang code. However, in certain circumstances, especially when you are to read variables values from various inputs, you may have to split variables’ declaration and values’ assignment. Let’s amend the code above to have these two blocks separately:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package main
import (
"fmt"
)
func main() {
// Declare variables
var username string
var ipAddress string
var reconnectingAttempts uint
var isReconnecting bool
// Assign values
username = "admin"
ipAddress = "10.10.10.10"
reconnectingAttempts = 3
isReconnecting = true
// Printing block
fmt.Printf(
"You are connecting to %v with username %v, with reconnecting set to %v and %v attempts.\n",
ipAddress,
username,
isReconnecting,
reconnectingAttempts,
)
}
What is different here is the following:
- Variables are declared using keyword var followed by the variable name and data type.
- For a declared variable assignment is done using symbol ‘=‘ rather than ‘:=‘.
Let’s execute the modified Go/Golang code:
1
2 $ go run main_static_types.go
You are connecting to 10.10.10.10 with username admin, with reconnecting set to true and 3 attempts.
There are no differences, which is what we expect.
With Pointers
In our final example we’ll show your how variable pointers are used:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 package main
import (
"fmt"
)
func main() {
// Declare variables
username := new(string)
ipAddress := new(string)
reconnectingAttempts := new(uint)
isReconnecting := new(bool)
// Assign values
*username = "admin"
*ipAddress = "10.10.10.10"
*reconnectingAttempts = 3
*isReconnecting = true
// Printing block
fmt.Printf(
"You are connecting to %v with username %v, with reconnecting set to %v and %v attempts.\n",
ipAddress,
username,
isReconnecting,
reconnectingAttempts,
)
fmt.Printf(
"You are connecting to %v with username %v, with reconnecting set to %v and %v attempts.\n",
*ipAddress,
*username,
*isReconnecting,
*reconnectingAttempts,
)
}
A few new things:
- To create a pointer to variable’s value, we use function new(). We’ll talk about functions in upcoming blogs.
- The result of the function execution is a pointer (memory address) to value of declared type.
- When you assign the value to such a variable, think that you actually need to write to that memory address, rather than directly to variable. To do so you use asterisk ‘*‘, which is called de-referencing operator.
- We have provided two blocks of printing for you to compare:
- Printing pointers values
- Printing values of memory addresses pointers point to
The result of this Go/Golang code execution:
1
2
3 $ go run main_pointers.go
You are connecting to 0xc00009e038 with username 0xc00009c050, with reconnecting set to 0xc00009a048 and 0xc00009a040 attempts.
You are connecting to 10.10.10.10 with username admin, with reconnecting set to true and 3 attempts.
We will get to pointers and why they are important, when we talk about functions.
Lessons in GitHub
You can find the final working versions of the files from this blog at out GitHub page.
Conclusion
Even just after three blog posts, you may see the difference in programming languages and their philosophies: Python is interpreted with dynamic typing, whilst Go is compiled with static typing. These capabilities matter to for everything: approach to programming, distributing applications across systems and performance, which we will talk more about later. Take care and good bye.
Support us
P.S.
If you have further questions or you need help with your networks, I’m happy to assist you, just send me message. Also don’t forget to share the article on your social media, if you like it.
BR,
Anton Karneliuk