Chapter 1: Embarking on Your Go Programming Adventure 🚀

DenishDenish
6 min read

Hello, hello, coding partners! ✨ Welcome to this weekend’s picnic if you are a coding beginner or just interested in expanding your skills. Today, we’re going to start with the very fundamental of Go that you should know. This amazing language is so easy to work with and offers the most returns in terms of time and convenience and that is why I recommend it whether you are a first timer or a professional.

The purpose of this post is to ease a reader into the language and illustrate it using simple, executable samples. Are you warmed up for this coding expedition? Let’s go! 🚀

Step 1: Setting Up Your Environment

Before we start coding, we need to set up our Go environment.

1.1 Install Go

  • Go to the Go Downloads page.

  • Download and install the appropriate version for your operating system.

1.2 Verify the Installation

Open your terminal or command prompt and type:

go version

You should see the installed version of Go.

Step 2: Your First Go Program

Let’s write our first program to print “Hello, World!” to the screen.

2.1 Create a New File

  • Open your text editor or IDE (like Visual Studio Code).

  • Create a new file called hello.go.

2.2 Write the Code

package main
import "fmt"
func main() {
    fmt.Println("Hello, World!")
}

2.3 Run the Program

  • Open your terminal and navigate to the folder where hello.go is saved.

  • Run the following command:

go run hello.go
Hello, World!

1.Introduction to Functions: Your Code’s Best Friends

Functions are the essential elements which can implement and control each Go program. You could consider them as small servants who do their part of the job. Here’s a simple function to greet the world:

package main
import "fmt"
func sayHello() {
    fmt.Println("Hello, World!")
}
func main() {
    sayHello()
}

However, whenever you feel like greeting someone you just call sayHello(). It’s that easy! You should make functions because the result is cleaner looking and easier to manage code.

Fun Challenge: Why not define a function that takes a name as a parameter then returns a greeting that includes the name?

2. Getting Multiple Values Back

One of the coolest features of Go is its ability to return multiple values from a function. This is super handy for things like error handling. Check this out:

func getTwo(x int) (int, int) {
    return x + 1, x + 2
}
func main() {
    a, b := getTwo(3)
    fmt.Println("Values returned:", a, b) // Outputs: Values returned: 4 5
}

Try This: Make a function that should accept two arguments and return their sum and product!

3. Error Handling Made Easy

Nobody enjoys mistakes but they are inevitable particularly when coding. Go approach errors in a very basic manner. Here’s how we can perform division while safely managing any potential errors:

func div(a int, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("can't divide by 0")
    }
    return a / b, nil
}
func main() {
    result, err := div(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }
}

Try It Out: Modify the div function to also handle negative numbers gracefully.

4. Let’s Chat: User Input

Want to interact with your users? Go makes it super simple to read input from the keyboard. Here’s how:

package main
import (
    "bufio"
    "fmt"
    "os"
)
func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter your name: ")
    name, _ := reader.ReadString('\n')
    fmt.Println("Hello,", name)
}

It’s just so simple that you can write only a few lines of codes and you can now, for instance, ask for your users’ names then greet them. Just run this code to see how you feel talking to your program!

Challenge: Let the user enter his/her age and then, depending upon the entered age, give him/her a particular message.

5. Variable Declaration: Pick Your Style

Similarly to other languages, in Go, there several ways to declare a variable exist. You can name it or use some short version you became used to!

package main
import "fmt"
func main() {
    var v1, v2 = 1.2, 3
    var vName string = "Monkey D.luffy"
    v3 := "Hello" // Short declaration
    fmt.Println(v1, v2, vName, v3)
}

Using :At its simplest, the format var := is used to declare variables without identification of their types. Go does that for you! Well, I can just say it’s like having a virtual assistant for coding.

Experiment: Get variables for different types and print them using only one print statement!

6. Understanding Data Types

Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows:

  1. Basic type: Numbers, strings, and booleans come under this category.

  2. Aggregate type: Array and structs come under this category.

  3. Reference type: Pointers, slices, maps, functions, and channels come under this category.

  4. Interface type

package main
import (
    "fmt"
    "reflect"
)
func main() {
    fmt.Println(reflect.TypeOf(42))      // int
    fmt.Println(reflect.TypeOf(3.14))    // float64
    fmt.Println(reflect.TypeOf(true))     // bool
    fmt.Println(reflect.TypeOf("Hello"))  // string
    fmt.Println(reflect.TypeOf('a'))      // rune
}

7. Type Casting: Change is Good

Sometimes, you need to change a variable's type. This is called type casting. Here’s how it works:

package main
import "fmt"
func main() {
    cV1 := 1.55
    cV2 := int(cV1) // Casting float to int
    fmt.Println("Converted value:", cV2) // Outputs: Converted value: 1
}

8. Constants: Unchanging Values

They are variables that remain constant all through your program. You declare them using the const keyword:

package main
import "fmt"
func main() {
    const pi = 3.14159
    fmt.Println("Value of pi:", pi)
}

It is particularly appropriate for any values that should not be changed dynamically, be they issue with mathematics constants or parameters of some program setting. Consider them as the facts about your program for them!

9. Conditional Statements: Make Decisions

Conditional operators are like familiar go ones so anyone who understands go would easily implement decision making. Here’s a simple age checker:

package main
import "fmt"
func main() {
    iAge := 11
    if (iAge >= 1) && (iAge <= 18) {
        fmt.Println("You can go to school")
    } else if (iAge >= 19) && (iAge <= 60) {
        fmt.Println("You can work")
    } else {
        fmt.Println("Enjoy retirement")
    }
}

10. Switch It Up

Switch statements provide for compact many-dimensional branching. It’s a great way to handle multiple conditions:

package main
import "fmt"
func main() {
    iAge := 18 
    switch iAge {
    case 16:
        fmt.Println("You can drive")
    case 18:
        fmt.Println("You can vote")
    case 21:
        fmt.Println("You can drink")
    default:
        fmt.Println("Enjoy your life")
    }
}

Conclusion: Join Me on This Journey!

Congratulations! 🎉 You’ve completed the first chapter of your Go programming journey! You’ve learned how to set up your environment, create functions, handle errors, read user input, and manipulate data.

In the next chapter, we will explore more advanced topics like data structures, loops, and how to work with collections of data.📚✨

If you found this chapter helpful, please consider subscribing to my blog for more insights and tutorials! 🌟 Your support means a lot and helps me continue sharing knowledge and resources.

Also, if you enjoyed this content, please leave a like ❤️! Your feedback is invaluable and encourages me to keep creating more valuable content.

Keep experimenting with the code, and don’t hesitate to modify and play around with it. Happy coding!💻🚀

0
Subscribe to my newsletter

Read articles from Denish directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Denish
Denish