Notifications 0

CodeGoundAI

ReadsNew

Speed TestNew

Code Grounds

RustGo LangNode JSPython 3C++JavaWeb(HTML, CSS, JS)

Data Grounds

RedisMongoDBPostgres

Tools New

Epoch ConverterCanvas Drawing boardBase64 EncodeBase64 DecodeJSON Web TokensJSON Diff

Popular

ReadsGrounds

Features

Realtime SharingShared OwnershipFast CompilationCloud Storage

Contact us

[email protected]

More to Explore

Sitemap

We @ CodeGroundAI

About UsPrivacy Policy

Sending Structs Between Goroutines in Go

Sultan Khan - March 29, 2025


Golang's concurrency model is one of its standout features, enabling developers to build highly concurrent and efficient programs. One common requirement is to send data between goroutines. This blog post will demonstrate how to send a struct from one goroutine to another using channels. We'll use a simple example with a person struct to illustrate the concept.


Introduction

In Go, goroutines are lightweight threads managed by the Go runtime. Channels are the conduits through which goroutines communicate. They provide a way to send and receive values of a specific type between concurrent goroutines. Let's explore how to send a struct via a channel between two goroutines.


Example: Sending a Struct

Here's a complete example in Go where we define a person struct, create two goroutines, and send an instance of the person struct from one goroutine to another via a channel.

The Code

package main

import (
"fmt"
"sync"
)

type person struct {
name string
age int
}

func main() {
var wg sync.WaitGroup
defer wg.Wait()
ch := make(chan person)

wg.Add(2)
go send(ch, &wg)
go receive(ch, &wg)
}

func send(c chan<- person, wg *sync.WaitGroup) {
defer wg.Done()
c <- person{name: "Shubham", age: 19}
close(c)
}

func receive(c <-chan person, wg *sync.WaitGroup) {
defer wg.Done()
p := <-c
fmt.Printf("Received: %+v\n", p)
}

Explanation

  1. Struct Definition: We define a simple person struct with two fields: name and age.
type person struct {
name string
age int
}
  1. Main Function: We initialize a sync.WaitGroup to wait for both goroutines to finish and create a channel to communicate person structs.
func main() {
var wg sync.WaitGroup
defer wg.Wait()
ch := make(chan person)

wg.Add(2)
go send(ch, &wg)
go receive(ch, &wg)
}
  1. WaitGroup: Ensures that the main function waits for both goroutines to complete before exiting.
  2. Channel: A typed channel for sending person structs.
  3. Sending Goroutine: The send function sends a person struct through the channel and then closes the channel.
func send(c chan<- person, wg *sync.WaitGroup) {
defer wg.Done()
c <- person{name: "Shubham", age: 19}
close(c)
}
  1. chan<- person: Indicates that this channel is only for sending person structs.
  2. close(c): Closes the channel after sending the data to signal that no more values will be sent.
  3. Receiving Goroutine: The receive function receives the person struct from the channel and prints it.
func receive(c <-chan person, wg *sync.WaitGroup) {
defer wg.Done()
p := <-c
fmt.Printf("Received: %+v\n", p)
}
  1. <-chan person: Indicates that this channel is only for receiving person structs.

Running the Code

When you run the above code, you should see the following output:

Received: {name:Shubham age:19}

This output demonstrates that the person struct was successfully sent from one goroutine to another via the channel.

Conclusion

Sending structs between goroutines in Go is straightforward with the use of channels. Channels provide a powerful mechanism for communication between goroutines, ensuring that data is safely passed around without the need for explicit locking. This simple example demonstrates the basics, and you can extend this pattern to more complex scenarios in your concurrent Go programs.



CodeGroundAI

CodeGroundAI is your all-in-one platform for seamless online coding. Whether you're a beginner or a pro, our IDE supports multiple programming languages, offers real-time collaboration, and provides a comprehensive toolkit for debugging, testing, and code execution.

Explore tools like the EPOCH Convertor, JSON Diff Checker, JWT Decoder, and Base64 Encoder/Decoder. With a real-time code-sharing platform and advanced comparison utilities, CodeGroundAI ensures you have everything you need for efficient development and accurate data handling.

Languages
  •  NodeJs
  •  Python
  •  Rust
  •  C++
  •  Java
  •  Golang
  •  Web
  •  MongoDB
  •  Redis
  •  Postgres
Tools
  •  Epoch Converter
  •  JSON Differentiator
  •  JWT Debugger
  •  Base64 Decode
  •  Base64 Encode
  •  Canvas
  •  Speed-Test
  •  Reads
Contact Us

Have questions or need support? Reach out to us for a smooth coding experience.

[email protected]

Connect with us on your favourite platform.

CodeGroundAI © 2024. All rights reserved.