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

标签 go concurrency

我正在使用 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

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

最佳答案

替换这一行:

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

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

并且还在 factorialViaChannel()

中用值 1 初始化变量 - computation

像这样:

var computation uint64 = 1 

关于go - 在 Go 中使用 channel ,我创建了一个返回地址的阶乘函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52320932/

相关文章:

Golang 通过 JSON 标签获取结构体的字段名

go - 如何将 slice 复制到自身

google-app-engine - GAE中如何导入本地Go包

android - Android SQLite 中的并发问题

scala - future 与速率限制器

javascript - 我可以在 golang 中定义/拼凑一个 javascript 类吗?

gob.Register 名称未在另一个包中注册接口(interface)

java - 线程转储分析(AWT-EventQueue 可运行但等待条件)

go - 使用 goroutine 进行矩阵乘法会降低性能

concurrency - 为什么parallelStream 使用的是ForkJoinPool,而不是普通的线程池?