DEV Community

Cover image for Getting your basics ready | Data types, Control flow, and Functions in GOLANG
Amal Satheesan
Amal Satheesan

Posted on • Edited on

Getting your basics ready | Data types, Control flow, and Functions in GOLANG

Data Types in Go: A Fun-filled Adventure

Ahoy there, fellow code wranglers! Today, we're delving into the marvelous world of data types in Go, also known as Golang. You might be wondering, "Why should I care about data types?" Well, my friends, data types are like the spice of programming. They add flavor, structure, and a touch of elegance to your code. So, let's embark on this data-driven journey, but before we get too carried away, let's put on our professional hats, just for a moment, shall we? ๐Ÿ˜Ž

Now, let's uncover the thrilling reasons why data types are the superheroes of the programming universe:

The Fantastic Functions of Data Types

  1. Data Organization: Imagine your code as a chaotic kitchen with ingredients scattered everywhere. Data types act like tidy organizers, neatly categorizing your data into logical containers.

  2. Data Validation: Have you ever tried to slice a tomato with a spoon? Data types ensure that you're using the right tool for the job by making sure your data is appropriate for the task at hand.

  3. Memory Efficiency: In the realm of data, space is precious. Data types are like expert Tetris players, ensuring that every byte is utilized efficiently.

  4. Error Prevention: Picture this: you're making a sandwich, and someone hands you a rubber duck instead of a tomato. Data types act as vigilant gatekeepers, preventing such absurd scenarios in your code.

  5. Code Clarity: Readable code is like a good book you can't put down. Proper data types make your code a page-turner, enhancing its clarity and maintainability.

  6. Functionality: Different data types come with their own bag of tricks. They bring built-in functions and methods to the party, making your life as a programmer easier and more fun.

  7. Data Integrity: Just like a good friend who keeps your secrets, data types maintain the integrity and consistency of data within your program, ensuring that nothing goes awry.

The Fabulous Four Categories of Data Types in Golang

Now, let's slice this data pie into four delightful categories:

  1. Basic types: These are the humble heroes of data types, including booleans, integers, floating-point numbers, and strings. They're like the bread and butter of programming.

  2. Aggregate types: These data types are the Frankenstein's monsters of the programming world. They're made up of other data types, such as arrays, slices, and structs. Imagine a sandwich made of smaller sandwiches!

  3. Reference types: These data types are the GPS of programming; they point to other data in memory. We're talking about pointers, slices, maps, functions, and channels. They help you navigate through the data wilderness.

  4. Interface types: Last but not least, interface types are like the universal remote controls of programming. They define a set of methods that any type can implement. It's the ultimate "plug-and-play" experience for your code.

Now, let's consult this handy table for a quick overview:

Data type Category Example
bool Basic true, false
int Basic 1, 100, -1000
uint Basic 1, 100, 1000
float32 Basic 3.141592653589793, 1.234567890123456, -1.234567890123456
float64 Basic 3.141592653589793, 1.234567890123456, -1.234567890123456
string Basic "Hello, world!", "1234567890", ""
[]int Aggregate [1, 2, 3, 4, 5]
[]string Aggregate ["Hello", "world", "!"]
struct { name string; age int } Aggregate { name: "Alice", age: 25 }
*int Reference var p *int = nil
map[string]int Reference map[string]int{"Alice": 25, "Bob": 30}
func() Reference func() { println("Hello, world!") }
chan string Reference chan string = make(chan string)
interface{} Interface var i interface{} = 10

Let's Inject Some Variable Fun into Go!

Ahoy, Go enthusiasts! We're setting sail on a thrilling journey into the heart of variables in Go. Buckle up because things are about to get wild in the world of data storage. ๐Ÿš€

Rules of the Variable Jungle

But before we jump into the variable jungle, let's lay down some ground rules:

  • Variables are like pets; they need names. So, we start with a letter or an underscore _.
  • They're not picky eaters; they can gobble up letters, digits, and underscores.
  • No spaces, please! Variables have a strict diet.
  • Finally, they can't pretend to be Go keywords. Let's not play dress-up with variables, okay?

Here are some examples of well-behaved variable names:

my_integer
my_float
my_string
my_array
my_slice
Enter fullscreen mode Exit fullscreen mode

The Grand Declaration

Now, let's talk about declaring variables. There are two ways to do it, and they each have their own flair:

1. The Normal Way

In the normal way, you play it by the book. You use the var keyword, followed by the variable name and the data type, like a proper introduction:

var my_integer int = 10
Enter fullscreen mode Exit fullscreen mode

2. The Short Variable Way

Now, here's where things get spicy! You can declare a variable in a shorter, snappier way using the := operator. It's like a casual nod instead of a formal handshake:

my_integer := 10
Enter fullscreen mode Exit fullscreen mode

But wait, there's a catch! The short variable declaration can only be used inside functions. It's like the cool kid who's only available at the weekend party.

Spot the Difference

So, what's the deal? Why choose one declaration over the other? Here's the scoop:

  • Normal Declaration: This one is like the boss telling you exactly what to do. It explicitly states the data type of the variable:

  • Short Declaration: It's like having a friend who just gets you. It infers the data type from the value you assign to it:

See the magic? In the short declaration, Go looks at the value and says, "Ah, this must be an integer!" It's like Go's version of mind-reading.

But remember, the normal declaration can be used anywhere, even outside functions. Meanwhile, the short declaration is a party animal, only allowed inside functions. ๐ŸŽ‰

Arrays and Slices in Go: A Tale of Two Data Structures

Ah, the dynamic duo of data structures in Go โ€“ arrays and slices! They're like Batman and Robin, always ready to save the day in your coding adventures. But don't be fooled, they have their own superpowers and quirks. Let's dive into the exciting world of arrays and slices!

Crafting Arrays and Slices

Array

To conjure an array in Go, you wield the following spell:

var myArray [array_size]data_type
Enter fullscreen mode Exit fullscreen mode

The array_size determines how many elements your array can hold, and data_type specifies the type of data it will store.

Slice

Now, let's talk about slices. To summon a slice, you chant:

var mySlice []data_type
Enter fullscreen mode Exit fullscreen mode

The data_type remains the same, but here's the kicker: slices are dynamic! They can grow and shrink as your code demands.

Accessing Elements from Array

To retrieve the treasure (element) from an array, you use this incantation:

myArray[index]
Enter fullscreen mode Exit fullscreen mode

The index is like a treasure map, guiding you to the element you seek. But beware, it must be a non-negative integer smaller than the array's size.

For slices, it's the same chant:

mySlice[index]
Enter fullscreen mode Exit fullscreen mode

Again, the index should be a non-negative integer, but this time, it should be smaller than the slice's length.

Enchanting Updates

To weave a new spell (update) on an array, you recite:

myArray[index] = new_value
Enter fullscreen mode Exit fullscreen mode

The index directs your magic to the specific element you wish to change, and new_value is the enchantment you bestow upon it.

For slices, it's dรฉjร  vu:

mySlice[index] = new_value
Enter fullscreen mode Exit fullscreen mode

The index still follows the same rules - non-negative and less than the slice's length.

Two sides: Arrays vs. Slices

Let's put on our boxing gloves and compare these titans:

Characteristic Array Slice
Size Fixed Dynamic
Access Square brackets Square brackets
Update Can be updated Can be updated
Comparison Can use == and != Can use == and !=
Passing to Functions Passed by value Passed by value

Whom to choose?

So, when do you call upon arrays, and when do you summon slices?

  • Arrays are like trusty Swiss army knives; use them when you know the exact size of your data collection.
  • Slices are your shape-shifters, perfect for dynamic data collections and when you want to share your data with functions without creating copies.

Remember, whether you're wielding arrays or unleashing slices, you've got the tools you need to conquer the coding kingdom! So, go forth, brave programmer, and may your arrays and slices always be in your favor! ๐Ÿฆธโ€โ™‚๏ธ๐Ÿš€

Navigating the Control Flow in Go

Ah, control flow statements in Go โ€“ the rudders that steer the ship of your program's execution! These are the tools that keep your code on the right track. Let's embark on a voyage through the seas of control flow!

If-Else: The Decision Maker

The trusty if-else statement is your first mate when it comes to making decisions in your code. It works like this:

if condition {
    // Code to be executed if the condition is true
} else {
    // Code to be executed if the condition is false
}
Enter fullscreen mode Exit fullscreen mode

The condition can be any Boolean expression. If it's true, the code in the if block sails smoothly. Otherwise, the ship navigates towards the else block.

Switch: The Multitasker

Next up is the switch statement, the multitasker of the control flow crew:

switch expression {
case value1:
    // Code to be executed if the expression equals value1
case value2:
    // Code to be executed if the expression equals value2
// ...
default:
    // Code to be executed if the expression doesn't match any cases
}
Enter fullscreen mode Exit fullscreen mode

The expression can take on various values. The switch statement evaluates it and compares it to each case value. If it matches one, the corresponding case block sets sail. If no match is found, the default block becomes the navigator's choice.

For Loop: The Repetition Enthusiast

The for loop is the workhorse of the control flow family:

for initialization; condition; post-iteration {
    // Code to be executed in the loop
}
Enter fullscreen mode Exit fullscreen mode
  • The initialization block sets the stage before the loop.
  • The condition is evaluated before each loop iteration. If it's true, the loop's code is executed; otherwise, the journey ends.
  • The post-iteration block ensures something happens after each iteration.

While Loop: The Persevering Explorer

Finally, we have the while loop, the tireless explorer:

while condition {
    // Code to be executed in the loop
}
Enter fullscreen mode Exit fullscreen mode

The condition is evaluated before each iteration. If it remains true, the loop keeps marching forward; otherwise, it bids adieu.

Declaring and Defining Functions in Go

To declare a function, you use the func keyword, followed by the function name and parameters in parentheses. The function body goes inside curly braces. For example, here's a function named add() that takes two integers and returns their sum:

func add(a int, b int) int {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

To define a function, simply assign a function body to it:

func add(a int, b int) int {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

Passing Arguments to Functions

To pass arguments to a function, list them in parentheses when you call the function:

result := add(1, 2)
Enter fullscreen mode Exit fullscreen mode

Arguments are passed by value, so changes inside the function don't affect the caller's scope.

Returning Values from Functions

Functions can return values using the return statement:

func add(a int, b int) int {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

The caller can access the returned value using a variable:

result := add(1, 2)
Enter fullscreen mode Exit fullscreen mode

Function Signatures

A function's signature is its name and the types of its parameters and return value:

func add(a int, b int) int
Enter fullscreen mode Exit fullscreen mode

This tells us add() takes two integers and returns an integer.

Named Returns

Named returns let you name the values returned from a function:

func add(a int, b int) (sum int) {
  sum = a + b
  return
}
Enter fullscreen mode Exit fullscreen mode

The caller can then access the returned value by name:

var sum int
sum = add(1, 2)
Enter fullscreen mode Exit fullscreen mode

Variadic Functions

Variadic functions take a variable number of arguments. Declare them with ... before the last parameter:

func sum(numbers ...int) int {
  var total int
  for _, number := range numbers {
    total += number
  }
  return total
}
Enter fullscreen mode Exit fullscreen mode

They can be called with any number of arguments:

result := sum(1, 2, 3)
Enter fullscreen mode Exit fullscreen mode

Now you're ready to navigate the high seas of control flow and harness the power of functions in Go! Fair winds and happy coding! ๐ŸŒŠ๐Ÿšข๐ŸŒŸ

Image description


Some challenge:

Problem Statement:

You are tasked with creating a command-line calculator program in the Go programming language. This calculator should be able to perform basic arithmetic operations, including addition, subtraction, multiplication, and division. The user will input two numbers and an operator, and the program will display the result of the operation.

Requirements:

  1. The calculator should support the following operations:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/)
Enter fullscreen mode Exit fullscreen mode
  1. The program should take three command-line arguments:
- The first argument should be a floating-point number (operand 1).
- The second argument should be one of the supported operators (+, -, *, /).
- The third argument should be another floating-point number (operand 2).
Enter fullscreen mode Exit fullscreen mode
  1. If the user provides incorrect or insufficient arguments, the program should display a usage message explaining how to use the calculator.

  2. For division, the program should check if the denominator is zero to avoid division by zero errors. If the denominator is zero, an error message should be displayed.

  3. The program should perform the requested operation and display the result with two decimal places.

Example Usage:

$ go run calculator.go 5 + 3
5.00 + 3.00 = 8.00 

$ go run calculator.go 10.5 - 3.2 
10.50 - 3.20 = 7.30 

$ go run calculator.go 2.5 * 4.0 
2.50 * 4.00 = 10.00 

$ go run calculator.go 6 / 0 
Error: division by zero
Enter fullscreen mode Exit fullscreen mode

I even spend so many times mitigating even small errors in the code. So refer this code if needed:
https://github.com/kutt27/go_series/blob/main/Beginner/calculator_cli/dev_calculator_program.go

To run the code, follow:
https://github.com/kutt27/go_series/blob/main/Beginner/calculator_cli/runnning_the_program.md

If you encounter any problem or any error, pull a PR.

Thanks again for reading!!! ๐Ÿ˜Š๐Ÿš€

Top comments (0)