【问题标题】:How to work with complex data type on nested structs on Hyperledger Fabric?如何在 Hyperledger Fabric 上的嵌套结构上处理复杂数据类型?
【发布时间】:2021-02-01 21:29:01
【问题描述】:

我想为公司创建一个管理客户的应用。对于这种情况,可能需要数组或切片。我创建了嵌套结构来管理客户,但一个新条目替换了前一个条目。我的链码的一部分:

mychaincode.go

type CompanyInfo struct {
    ObjectType   string `json:"docType"`
    Company_Name string  `json:"company_name"`
    Customers        map[string][]Users `json:"customers"`
}

type Users  struct {
    Name         string `json:"name"`
    Surname      string `json:"surname"`
    Email        string `json:"email"`
}
func (c *MyChaincode) addCustomers(stub shim.ChaincodeStubInterface, args []string) pb.Response {
    ObjectType := "Myobject"
    companyname := args[0]
    name := args[1]
    surname := args[2]
    email := args [3] 
    authUser := CompanyInfo{}
    authUser.Customers["key"] = []Users{
            {
                Name:         name,
                Surname:      surname,
                Email:        email,
            },
        }

    companyUser := CompanyInfo {objectType, companyname,authUser.Customers}
    companyUserJSONasBytes, err := json.Marshal(companyUser)
    if err != nil {
        return shim.Error(err.Error())
    }

    err = stub.PutState(companyname, companyUserJSONasBytes)
    if err != nil {
        return shim.Error(err.Error())
    }

Visual Studio 无法识别任何错误,但是当我尝试在本地网络上调用时,链码已退出

docker logs dev-peer0.example.com-mychaincode-1.0的输出:

恐慌:分配给 nil 映射中的条目 恐慌:运行时错误:无效的内存地址或 nil 指针取消引用

【问题讨论】:

  • 看起来代码完全错误。检查这一行struct1.Users = append(struct1.Users, struct2)不应该添加到struct1.Customers吗?
  • @myeongkil kim 我认为最好的选择是使用地图嵌套切片。我更新了我的代码和收到的错误。我认为嵌套切片没有接收值

标签: go hyperledger-fabric


【解决方案1】:

我发现了初始化切片所需的问题。

    authUser := CompanyInfo{}
    authUser.Customers = make(map[string][]Users)
    authUser.Customers["key"] = []Users{
            {
                Name:         name,
                Surname:      surname,
                Email:        email,
            },
        }

【讨论】:

    【解决方案2】:

    尝试这样,我已经硬编码了这些值,但在你的情况下你必须提供它们。

    users := []Users{
            Users{
                Name:    "Peter",
                Surname: "a",
                Email:   "a@mail.com",
            },
        }
        t := Users{
            Name:    "Pony",
            Surname: "b",
            Email:   "b@mail.com",
        }
    
        comp := CompanyInfo{}
        comp.ObjectType = "abc"
        comp.Company_Name = "company 1"
        comp.Customers = users
        comp.Customers = append(comp.Customers, t)
        fmt.Println(comp)
    

    你可以在这里找到完整的例子https://play.golang.org/p/yfgxVhcwjYZ

    【讨论】:

      猜你喜欢
      • 2020-02-20
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2020-05-31
      • 2020-12-27
      • 2013-11-23
      相关资源
      最近更新 更多