A
A
ajlhimik2018-03-18 22:18:31
go
ajlhimik, 2018-03-18 22:18:31

Channels in golang, but what about that one?

package main
import "fmt"
 
func main() {
     
    intCh := make(chan int, 2) 
    go factorial(5, intCh)
    fmt.Println(<-intCh)
    fmt.Println("The End")
}
 
func factorial(n int, ch chan<- int){
     
    result := 1
    for i := 1; i <= n; i++{
        result *= i
    }
    ch <- result
}

here is the code
the factorial() function takes n and the channel ch, the question is - ch is:
1. unbuffered channel created by declaring the factorial functions that copies the data intCh // it is unlikely where the results of the factorial() functions will be in intCh
2. since intCh and ch are different (the first is bidirectional and the second is unidirectional), the latter does not exactly copy the first, maybe it (channel ch) is something like a pointer (for channels :D ) for intCh in
general, how can I understand why fmt.Println(<-intCh) gives 120
from where did the data turn out to be in the intCh channel?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sly_tom_cat ., 2018-03-19
@Sly_tom_cat

There is only one channel in the code: intCh, when factorial is called, the channel is passed by reference (it is the only way it is passed) and inside factorial this single channel is called ch and, in addition, it has a restriction that this channel can only be used to output to it (the restriction is imposed in function parameter declarations).
No magic - the channel was announced, transmitted, read from it.

R
RidgeA, 2018-03-18
@RidgeA

The channel is passed by reference. The fact that the channel in the function is unidirectional does not change or copy the original channel in any way, it just cannot be used inside the function in any other way (the channel for writing cannot be read, the channel for reading cannot be written)
https://play.golang.com/p /v00VjMZHqGu

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question