Type Declaration: GO lang

Type Declaration: GO lang

ยท

3 min read

The TYPE declaration allows us to create 'named' data types, which are based on existing data types, and its main objective is to allow the creation of variables of the same type with different characteristics.

Typically, TYPE declarations appear at the package level so that they can be used by any .go file in the package. If the name of the named type being created starts with an uppercase letter, this named type can be used by any package.

Have you ever heard that you can't add apples and oranges? Well, GO allows us to control this, and to better understand this theory, let's work on the following example:

Let's create 2 variables that represent 2 different units of time (seconds and minutes).

var seconds int
var minutes int

Okay, now let's assign values:

seconds = 15
minutes = 30

What happens if we try to add these 2 units of time?

sum := seconds + minutes

So far, there is no syntax error, as the program would compile, and the result of the "sum" variable will be 45. But 45 what? They are not seconds, and they are not minutes either. So we must control this so that we cannot add 'apples and oranges'. For this, we use the type declaration. Instead of declaring variables with the var keyword, we use the type keyword:

type seconds int
type minutes int

Now, we have created two named data types that, although belonging to the same base data type, have different characteristics. So let's create variables that belong to these data types:

var sec seconds = 15
var min minutes = 30

And what happens now if we try to add them?

sum := sec + min

The compiler will show a different data type error (mismatched), so we are already preventing the addition of 'apples and oranges'. However, we want to be able to get a total in seconds when adding, so what we need to do is create a function that converts minutes to seconds like this:

func minutesToSeconds(m minutes) seconds {
    return seconds(m * 60)
}

Notice how in the function (which we will talk about later), it returns seconds(m 60). This is because we can multiply minutes by 60 to get seconds, but we must cast the result; otherwise, the result will again return minutes multiplied by 60. Casting: seconds(min 60) is valid since the value returned by (min*60) is of type integer (the base type of minutes and seconds), so we can convert the result to seconds. So, the sum of seconds and minutes would look like this:

sum := sec + minutesToSeconds(min)

More such articles:

https://medium.com/techwasti

https://www.youtube.com/@maheshwarligade

https://techwasti.com/series/spring-boot-tutorials

https://techwasti.com/series/go-language

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

ย