OK keyword in go
📘 Golang ok
ok সাধারণত ব্যবহৃত হয়:
Channel receive check
Map lookup check
Type assertion check
এটি সবসময় boolean value হিসেবে আসে এবং বলে দেয় “operation successful কি না”
1️⃣ Channel Receive Check
ch := make(chan int, 1)
ch <- 10
val, ok := <-ch
fmt.Println(val, ok)
Output:
10 true
Explanation:
val= channel থেকে valueok= channel open আছে কিনাযদি channel closed থাকে,
okহবেfalse
close(ch)
val, ok := <-ch
fmt.Println(val, ok)
Output:
0 false
✅ Deadlock বা closed channel detect করতে ব্যবহার করা হয়
2️⃣ Map Lookup Check
m := map[string]int{
"a": 1,
"b": 2,
}
val, ok := m["a"]
fmt.Println(val, ok) // 1 true
val, ok = m["c"]
fmt.Println(val, ok) // 0 false
Explanation:
m["key"]normal value দিলে 0 আসে যদি key না থাকেokদিয়ে আমরা জানি key exist করে কিনাThis is idiomatic Go
3️⃣ Type Assertion Check
var i interface{} = "hello"
s, ok := i.(string)
fmt.Println(s, ok) // hello true
f, ok := i.(float64)
fmt.Println(f, ok) // 0 false
Explanation:
okবলে type assertion successful কিনানাও মানে type mismatch হলে panic থেকে বাঁচায়
4️⃣ Channel + For Loop + ok (Receive Until Close)
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 3
close(ch)
for {
val, ok := <-ch
if !ok {
break
}
fmt.Println(val)
}
Output:
1
2
3
Explanation:
okfalse হলে channel closed → loop breakidiomatic way to drain a channel
5️⃣ Combined Example (Map + Type Assertion + Channel)
package main
import "fmt"
func main() {
// Map lookup
m := map[string]interface{}{"name": "Ali"}
val, ok := m["name"]
if ok {
str, ok := val.(string)
if ok {
fmt.Println("Name is:", str)
}
}
// Channel receive
ch := make(chan int, 2)
ch <- 100
close(ch)
v, ok := <-ch
if ok {
fmt.Println("Received:", v)
} else {
fmt.Println("Channel closed")
}
}
Output:
Name is: Ali
Received: 100
🔑 Key Takeaways
| Usage | Example | Meaning |
|---|---|---|
| Map existence | val, ok := m["key"] | key আছে কি না |
| Channel receive | val, ok := <-ch | channel closed কি না |
| Type assertion | val, ok := i.(type) | type assertion successful কি না |
Important:
okএর ব্যবহার Go idiomatic styleএগুলো সব boolean
Program কে safe, readable & robust রাখে
🧠 Mental Model
ok= “Did it work?”Channel থেকে value → কাজ করল কি না
Map থেকে key → key আছে কি না
Type assertion → type match করল কি না
🔥 Interview Tip
Q: What is ok in Go?
A:
It’s a boolean idiom to check if an operation succeeded, commonly used with channels, maps, and type assertions.