Header Ads

Header ADS

OK keyword in go

📘 Golang ok

ok সাধারণত ব্যবহৃত হয়:

  1. Channel receive check

  2. Map lookup check

  3. 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:

  1. val = channel থেকে value

  2. ok = channel open আছে কিনা

  3. যদি 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:

  1. m["key"] normal value দিলে 0 আসে যদি key না থাকে

  2. ok দিয়ে আমরা জানি key exist করে কিনা

  3. 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:

  1. ok বলে type assertion successful কিনা

  2. নাও মানে 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:

  1. ok false হলে channel closed → loop break

  2. idiomatic 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

UsageExampleMeaning
    Map existenceval, ok := m["key"]                      key আছে কি না
   Channel receive           val, ok := <-ch                       channel closed কি না
     Type assertionval, ok := i.(type)                  type assertion successful কি না

Important:

  1. ok এর ব্যবহার Go idiomatic style

  2. এগুলো সব boolean

  3. Program কে safe, readable & robust রাখে


🧠 Mental Model

  1. ok = “Did it work?”

  2. Channel থেকে value → কাজ করল কি না

  3. Map থেকে key → key আছে কি না

  4. 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.



Powered by Blogger.