Saturday, May 4, 2024
HomeGolangA query about channels - Getting Assist

A query about channels – Getting Assist


Hello,

I hope this isn’t a boneheaded query. I’ve searched on this discussion board however haven’t seen fairly what I’m in search of. This submit about doable race situations appears a probable match.

I’ve been channels on golangdocs.com, sending customized knowledge through channels. I’ve made one tiny change, including a Printf assertion to the referred to as operate. I’ll paste the entire code right here so it’s straightforward to see.

bundle principal

import (
	"fmt"
)

sort Individual struct {
	Title string
	Age  int
}

func SendPerson(ch chan Individual, p Individual) {
	ch <- p
	fmt.Printf("SendPerson %vn", p)
}

func principal() {

	p := Individual{"John", 23}

	ch := make(chan Individual)

	go SendPerson(ch, p)

	title := (<-ch).Title
	fmt.Println(title)
}

If I run this code a couple of occasions I often see simply John. Typically I see:

SendPerson {John 23}
John

I don’t fairly perceive why. I believed this was an error on my half as I ought to have put the Printf assertion within the referred to as operate earlier than the channel dealing with half as a result of I needed to see what I used to be receiving (that was the aim of including the Printf within the first place). However then I considered it a bit extra. Why do I see this typically? I’d anticipate to see it all the time or by no means, however not typically seemingly at random. I’m not certain if that is linked to being buffered or unbuffered.

Can any individual level me in the correct route?

Many thanks,
John.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments