Golang (Go) Tutorial - Channels - Communication

Unlock Premium Features: AI explanations (Hinglish), Indian voice & Videos
Sign Up Free

๐Ÿ“ก Channels - Goroutines Ko Connect Karo

๐ŸŒŸ Real Life Analogy:

๐Ÿ“ž WhatsApp Chat:
Person A sends โ†’ Channel โ†’ Person B receives
Two goroutines communicate karne ka raasta!

๐Ÿญ Factory Assembly Line:
Worker 1 โ†’ Conveyor belt โ†’ Worker 2
Channel = Conveyor belt (data transfer karta)

๐Ÿ“ฌ Post Office:
Sender โ†’ Mailbox (channel) โ†’ Receiver

๐ŸŽฏ Channel Kya Hai?

  • Goroutines ke beech communication
  • Data safely transfer karo
  • Synchronization automatically
  • Type-safe (sirf ek type ka data)

๐Ÿ“ Channel Syntax

Create & Use
// Create channel
ch := make(chan int)

// Send data (arrow towards channel)
ch <- 42

// Receive data (arrow from channel)
value := <-ch

๐Ÿ“Š Channel Types

TypeDescriptionExample
UnbufferedDirect handoffmake(chan int)
BufferedQueue with capacitymake(chan int, 5)
Send-onlychan<- intOnly send
Receive-only<-chan intOnly receive

๐Ÿ”„ Unbuffered vs Buffered

Unbuffered Channel

Analogy: Phone call - dono ka saath hona zaroori

ch := make(chan int)
// Sender waits until receiver ready
Buffered Channel

Analogy: Mailbox - chhod do, baad mein le lenge

ch := make(chan int, 3)  // 3 messages store kar sakta
// Up to 3 sends without waiting

โš ๏ธ Deadlock Warning!

Agar send kiya lekin receive nahi โ†’ Program hang!
Always ensure receiver exists for sender.

๐Ÿ’ก Common Patterns

1. Producer-Consumer
// Producer
go func() {
    ch <- data
}()

// Consumer
result := <-ch
2. Select Statement (Multiple Channels)
select {
case msg1 := <-ch1:
    // Handle ch1
case msg2 := <-ch2:
    // Handle ch2
case <-time.After(1 * time.Second):
    // Timeout
}

๐Ÿค– AI Tutor Unlock Karo!

Apni language mein coding seekho - Hindi, Marathi, Gujarati aur 10+ Indian languages mein!

  • Hinglish mein explanations
  • Real-life examples
  • Beginner-friendly
Free Signup Karo

Example

ch := make(chan int)
ch <- 42        // Send
value := <-ch   // Receive