在 Go 中使用通道,我创建了一个返回地址的阶乘函数

我正在使用 Channels 和 Go Routines 来练习伪并发。出于某种原因,我的 Factorial 函数似乎返回一个地址,而不是实际的整数值。这是我的代码:


package main


import (

    "fmt"

)


func main() {

    c := make(chan uint64)

    go factorialViaChannel(8, c)

    f := c //Assign go channel value to f

    fmt.Println("The Factorial of 8 is", f)

    myNums := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9}

    product := make(chan int64)

    go multiply(myNums, product) //create go routine pseudo thread

    result := <-product

    fmt.Println("The Result of this array multipled computation is", result)


}


func factorialViaChannel(value int, factorial chan uint64) {

    var computation uint64

    if value < 0 {

        fmt.Println("Value can not be less than 0")


    } else {

        for i := 1; i <= value; i++ {

            computation *= uint64(i)

        }


    }

    factorial <- computation


}


func multiply(nums []int64, product chan int64) { //multiply numerous values then send them to a channel

    var result int64 = 1

    for _, val := range nums {

        result *= val

    }

    product <- result //send result to product

}

这是我的结果:


$ go run MultipleConcurrency.go

The Factorial of 8 is 0xc42000c028

The Result of this array multipled computation is 362880

为什么打印内存地址而不是值?我有点困惑。谢谢!


梵蒂冈之花
浏览 141回答 2
2回答

繁华开满天机

替换这一行:f&nbsp;:=&nbsp;c&nbsp;//Assign&nbsp;go&nbsp;channel&nbsp;value&nbsp;to&nbsp;f和f&nbsp;:=&nbsp;<-c&nbsp;//Assign&nbsp;go&nbsp;channel&nbsp;value&nbsp;to&nbsp;f并初始化变量 -computation值1在factorialViaChannel()像这样:var&nbsp;computation&nbsp;uint64&nbsp;=&nbsp;1

拉丁的传说

我想通了,问题已在下面更正:package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; factorial := make(chan uint64)&nbsp; &nbsp; go factorialViaChannel(8, factorial)&nbsp; &nbsp; f := <-factorial //Assign go channel value to f&nbsp; &nbsp; fmt.Println("The Factorial of 8 is", f)&nbsp; &nbsp; myNums := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9}&nbsp; &nbsp; product := make(chan int64)&nbsp; &nbsp; go multiply(myNums, product) //create go routine pseudo thread&nbsp; &nbsp; result := <-product&nbsp; &nbsp; fmt.Println("The Result of this array multipled computation is", result)}func factorialViaChannel(value int, factorial chan uint64) {&nbsp; &nbsp; var computation uint64 = 1&nbsp; &nbsp; if value < 0 {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Value can not be less than 0")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; for i := 1; i <= value; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; computation *= uint64(i)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; factorial <- computation}func multiply(nums []int64, product chan int64) { //multiply numerous values then send them to a channel&nbsp; &nbsp; var result int64 = 1&nbsp; &nbsp; for _, val := range nums {&nbsp; &nbsp; &nbsp; &nbsp; result *= val&nbsp; &nbsp; }&nbsp; &nbsp; product <- result //send result to product}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go