【问题标题】:One to many relationship in NEAR protocol using rustNEAR 协议中使用 rust 的一对多关系
【发布时间】:2020-09-26 05:17:30
【问题描述】:

我正在尝试使用 near_sdk MapVector 使用一对多关系。

use near_sdk::collections::Map;
use near_sdk::collections::Vector;

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct ProfileDetails {
    profileTags: Map<String, IdProducts>,
}

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct Products { 
    product_name: String,
    product_details: String,
} 

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct IdProducts {
      products: Vector<Products>,
}

对于 rust 本机集合,它是使用推送方法完成的,例如

 let mut hash_map: HashMap<u32, Vec<Sender>> = HashMap::new()
 hash_map.entry(3)
      .or_insert_with(Vec::new)
      .push(sender)

如何使用近协议集合推送?

#[near_bindgen]
impl ProfileDetails {
    pub fn set_profile(&mut self, product_name:String, product_details:String) {
        let account_id = env::signer_account_id();
        p = Products {
            product_name,
            product_details
        };
        self.profileTags.insert(&account_id, ???);

    }
}

Solidity 示例在这里:https://ethereum.stackexchange.com/a/39705/56408

【问题讨论】:

    标签: rust nearprotocol


    【解决方案1】:

    首先,您只能在一个代表合约本身的结构上使用#[near_bindgen]。要实现set_profile,您可以创建一个带有适当前缀的持久向量(例如account_id)。所以它看起来像

    let account_id = env::signer_account_id();
    p = Products {
        product_name,
        product_details
    };
    let mut id_products = Vector::new(account_id.into_bytes());
    id_products.push(&p);
    self.profileTags.insert(&account_id, &id_products);
    

    如果你的集合很小,你也可以使用标准库中的Vec

    【讨论】:

    • new 给出错误:让 mut products_list = Vector::new(id); | ----------------- ^^^^^^^^^^^ 无法推断类型参数T的类型
    • 可以注释变量:let mut id_products: Vector&lt;IdProducts&gt; = ...
    猜你喜欢
    • 2022-01-08
    • 2021-01-10
    • 2021-01-12
    • 2021-11-20
    • 2022-01-20
    • 2022-08-03
    • 2022-07-14
    • 2020-08-12
    • 2021-12-29
    相关资源
    最近更新 更多