登录
首页 >  Golang >  Go问答

GoSpace的Get功能无法正常运行

来源:stackoverflow

时间:2024-02-26 12:06:25 472浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《GoSpace的Get功能无法正常运行》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我是 go 新手,但我似乎无法让这段代码工作(按照这个例子):

package main

import (
    "fmt"
    . "github.com/pspaces/gospace"
)

func p1(board *space, l int) {
  mult := 1
  for i := 1; i <= l; i++ {
      mult = mult * i
  }

  t, e := board.putp("p1", mult)
  fmt.printf("error 1: %v  (tuple: %v)", e, t)  // error 1: <nil> (tuple: "p1", 120)
  
  fmt.printf("multiplication by process1 was placed in the tuplespace\n")
}

func p2(board *space, k int, m int) {
  mult := 1
  for i := k; i <= m; i++ {
      mult = mult * i
  }

  t, e := board.putp("p2", mult)
  fmt.printf("error 2: %v (tuple: %v)", e, t)  // error 2: <nil> (tuple: "p2", 30240)
  
  fmt.printf("multiplication by process2 was placed in the tuplespace\n")
}

func p(board *space) {
    fmt.printf("in the p\n")

    var r1 int
    var r2 int
    
    board.get("p1", &r1)
    fmt.println("process took value from p1")
    board.get("p2", &r2)
    fmt.println("process took value from p2")
    fmt.println(r1)  // 0  --> problem here
    fmt.println(r2)  // 0  --> problem here
    
    //r := r1 * r2
    //board.put("p", r)
    fmt.printf("multiplication of process1 and process2 was performed and the result was placed in the tuplespace\n")
}

func main() {
    board := newspace("board")
    go p1(&board, 5)
    go p2(&board, 6, 10)

    fmt.println("write 'start' in order to start final computation\n ")
    var input string
    fmt.scanln(&input)
    
    fmt.println(board.size())
    go p(&board)
    board.query("done")
}

当我写这个问题时,我找到了一种解决方法:

tp, e := board.Get("P1", &r1)
fmt.Println("Process took value from p1")
fmt.Printf("Tuple: %v, Error %v\n", tp, e)  // Tuple: "P1, 120", Error <nil>

但是,这仍然不是使用 get 的预期方式(并且 r1 仍然为 0)。我只想获取 p1 的“值”,而不是完整的元组。


正确答案


看起来这个例子有问题。 get() 的参数用于构建过滤结果的模式。因此,您可以通过将指针传递给变量来传递实际值或按类型进行过滤。

您应该从元组中获取值,例如这样:r1 = (t.getfieldat(1)).(int)

因此链接的示例可以通过以下方式修复:

package main

import (
        "fmt"
        . "github.com/pspaces/gospace"
)

func main() {
        fridge := NewSpace("fridge")

        // Add some stuff to the grocery list.
        fridge.Put("milk", 2)
        fridge.Put("butter", 3)

        // Retrieve one item via pattern matching.
        var item string
        var quantity int
        if t, e := fridge.Get(&item, &quantity); e == nil {
                quantity = (t.GetFieldAt(1)).(int)
                item = (t.GetFieldAt(0)).(string)
        }

        // Print the item retrieved.
        fmt.Printf("%s: (%v, %v)\n", "Grocery item", item, quantity)
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>