Day One Golang Fundamentals

·

3 min read

Hey there👋, geeks!!! I hope this article found you really well. If you are new to this series I recommend you check out the Day Zero Golang Fundamentals article first.

In this article I will cover two fundamental Golang topics:

  1. Functions and Return values.
  2. Pointers.

Functions:

A Function in Golang:

  1. Is declared using the func keyword.
  2. Can take zero or more arguments.
  3. Can return zero or more values/parameters.
  4. Can be named or could be anonymous.
/* A function that takes in two integer variables and returns a value of integer type. */

func add(x int, y int) int {
    return x + y
}

// Calling the function with two arguments.

add(3,5)

As Go is a statically typed language it's essential to declare the type of arguments and the return type if the function returns something.

But unlike in C/C++ where we declare the type before the variable name, in Go the type comes after the variable name.

func add(x int, y int) {}

Also, we have the provision to declare a single type that applies to all parameters, which comes in handy at places where multiple parameters share the same type.

func add(x, y int) int {
    return x + y
}

Now let's look at, what the code implementation of returning multiple values looks like:

/* The additional code footprint of returning multiple values is 
clearly distinct here. i.e. all the expected return types listed 
as follows: (int, int) */
func operations(x, y int) (int, int) {
    add := x+y
    sub := x-y
    return add, sub
}

As a side note remember that Golang allows naming the returned parameters like:

However, doing such a thing is not highly advocated.

func operations(x, y int) (add, sub int) {
    add := x+y
    sub := x-y
    return //returns add and sub values implicitly
}

Pointers:

Yes, you heard it right, we have pointers in Go. But wait, no pointer arithmetic like in C/C++.

Pointers come in handy when we want to pass the arguments by reference, which cuts through Go's default way of passing arguments by value(i.e. by copying them).

To get the pointer of a value, use the & symbol in front of the value.

To dereference a pointer, use the * symbol.

func main() {
    x := 458
    y := &x
    z := *y
    fmt.Printf("The value of x is %d, the pointer y which points to address of x as %d and when dereferenced as z we get the original value as %d.", x, y, z)
}

o/p:

The value of x is 458, the pointer y to which points to address of x as 824634466336 and when dereferenced as z we get the original value as 458.

That's it for this article folks, I suggest you play around with the code examples on the officially builtin Golang code playground here.

Thank you, for reading till the end. If you like the article pass it on to the next geek you know. If you hate it, help me improve my commenting.