我应该如何在golang中传递param?

时间:2018-06-10 03:55:13

标签: go reflection

我有以下完整代码:

我希望golang中的字符串转换映射,并使用golang reflect。

以下代码简化了我的项目。

#include <iostream>
#include <boost/thread/barrier.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>

class MyClass {
    int m_x;
    bool m_terminate;
    boost::thread_group m_threads;
    boost::barrier m_workToDo, m_allDone;

    void threadFun()
    {
        while(true) {
            m_workToDo.wait();
            if (m_terminate)  // read m_terminate, IS_SAFE?
                 break;
            // do something with x
            std::cout << m_x << "\n";  // read m_x, IS_SAFE?
            m_allDone.wait();
        }
    }
public:
    MyClass(size_t n) : m_terminate(false), m_workToDo(n), m_allDone(n)
    {
        // create and launch a thread pool
        for (size_t i = 0; i < n-1; ++i) 
             m_threads.create_thread(boost::bind(&MyClass::threadFun, this));
    }

    ~MyClass()
    {
        // destroy thread pool
        m_terminate = true; // write m_terminate, IS_SAFE?
        m_workToDo.wait();   // (n-1) thread waiting: unleash all threads
        m_threads.join_all();
    }

    void doSomeWork(int x) {
        m_x  = x;         // write m_x, IS_SAFE?
        m_workToDo.wait(); // (n-1) thread waiting: unleash all threads
        m_allDone.wait(); // (n-1) thread waiting: unleash all threads
    }
};

然后运行它并得到结果:

(async () => console.log(String(await require('fs').promises.readFile('./file.txt'))))();

我希望得到以下结果:

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    jsonStr := `{"name": "thinkerou", "age": 31, "balance": 3.14}`

    var a map[string]interface{}
    var value reflect.Value = reflect.ValueOf(&a)

    // call function and pass param
    f(jsonStr, value)

    // print result
    fmt.Println(value.Kind(), value.Interface())
}

func f(v string, value reflect.Value) {
    personMap := make(map[string]interface{})

    err := json.Unmarshal([]byte(v), &personMap)

    if err != nil {
        panic(err)
    }

    value = reflect.Indirect(value)
    value = reflect.MakeMap(value.Type())
    for k, v := range personMap {
        // set key/value
        value.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v))
    }

    // print result
    fmt.Println(value.Kind(), value.Interface())
}

我应该如何通过map map[age:31 balance:3.14 name:thinkerou] ptr &map[] param?谢谢!

1 个答案:

答案 0 :(得分:3)

您应该可以使用type assertion

从界面中获取地图
a := i.(map[string]interface{})

请参阅“Convert Value type to Map in Golang?

我修改了您的code here 请注意,我不会尝试改变f(value)参数,而是将其返回。

func f(v string, value reflect.Value) reflect.Value {
  ...
  return value 
}

所以代码变成:

value = f(jsonStr, value)
fmt.Println(value.Kind(), value.Interface().(map[string]interface{}))