Skip to main content

Command Palette

Search for a command to run...

Go Series Part 5: Comma OK Syntax or Error OK Syntax

Updated
2 min read
Go Series Part 5: Comma OK Syntax or Error OK Syntax
N

👋 Welcome to my Hashnode profile! I'm a passionate technologist with expertise in AWS, DevOps, Kubernetes, Terraform, Datree, and various cloud technologies. Here's a glimpse into what I bring to the table: 🌟 Cloud Aficionado: I thrive in the world of cloud technologies, particularly AWS. From architecting scalable infrastructure to optimizing cost efficiency, I love diving deep into the AWS ecosystem and crafting robust solutions. 🚀 DevOps Champion: As a DevOps enthusiast, I embrace the culture of collaboration and continuous improvement. I specialize in streamlining development workflows, implementing CI/CD pipelines, and automating infrastructure deployment using modern tools like Kubernetes. ⛵ Kubernetes Navigator: Navigating the seas of containerization is my forte. With a solid grasp on Kubernetes, I orchestrate containerized applications, manage deployments, and ensure seamless scalability while maximizing resource utilization. 🏗️ Terraform Magician: Building infrastructure as code is where I excel. With Terraform, I conjure up infrastructure blueprints, define infrastructure-as-code, and provision resources across multiple cloud platforms, ensuring consistent and reproducible deployments. 🌳 Datree Guardian: In my quest for secure and compliant code, I leverage Datree to enforce best practices and prevent misconfigurations. I'm passionate about maintaining code quality, security, and reliability in every project I undertake. 🌐 Cloud Explorer: The ever-evolving cloud landscape fascinates me, and I'm constantly exploring new technologies and trends. From serverless architectures to big data analytics, I'm eager to stay ahead of the curve and help you harness the full potential of the cloud. Whether you need assistance in designing scalable architectures, optimizing your infrastructure, or enhancing your DevOps practices, I'm here to collaborate and share my knowledge. Let's embark on a journey together, where we leverage cutting-edge technologies to build robust and efficient solutions in the cloud! 🚀💻

Introduction

Have you ever come across a statement like this?

func main() {
    i := "hello world"
    n, ok := i.(int)
    if ok {
        fmt.Println("n:", n)
    } else {
        fmt.Println("not an int")
    }
}

In Go, there's no try-catch block like in Java or Scala. While it might seem odd at first, Go's error handling mechanisms grow on you, enabling you to handle errors like a pro. One such mechanism is the "comma ok" syntax, used in various scenarios to test for success or failure.

Example 1: Testing if a Key Exists in a Map

Let's start with a simple example where we check if a key exists in a map.

package main

import (
    "fmt"
)

func main() {
    stocks := map[string]float64{
        "GOOG": 1500.0,
        "AMZN": 3100.0,
    }

    symbol := "AAPL"
    price, ok := stocks[symbol]
    if ok {
        fmt.Printf("%s is priced at $%.2f\n", symbol, price)
    } else {
        fmt.Printf("%s not found in the map\n", symbol)
    }
}

Output:

AAPL not found in the map

Explanation:

  • We have a map stocks with some stock prices.

  • We check if the key "AAPL" exists in the map using the comma ok syntax.

  • If the key exists, we print its price; otherwise, we print a message indicating it was not found.

Example 2: Type Assertion

Another common use of the comma ok syntax is to check if an interface value is of a specific type.

package main

import (
    "fmt"
)

func main() {
    var i interface{} = "hello"

    if s, ok := i.(string); ok {
        fmt.Printf("The string is: %s\n", s)
    } else {
        fmt.Println("The value is not a string")
    }
}

Output:

The string is: hello

Explanation:

  • We have an interface variable i holding a string value.

  • Using the comma ok syntax, we check if i is of type string.

  • If it is, we print the string; otherwise, we print a message indicating it is not a string.

Conclusion

The "comma ok" syntax is a useful pattern in Go for error handling and type assertions. By using this pattern, you can make your code more robust and handle different conditions gracefully.

Next, we will cover conversion in GoLang

More from this blog

NavyaDevops

78 posts

DevOps Engineer with advanced skills in cloud technologies. Proven track record in optimizing development and deployment processes. Dedicated to innovation and scalability in software development.