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 thecomma 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 ifi
is of typestring
.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