将 Base64VecU8 解码为 Vec<u8> 并与另一个 Vec <u8>合并



我正在尝试将JSON字符串合并为Vec<u8>,并解码Base64VecU8值的结果:

pub fn decode_and_merge(&mut self, args: Base64VecU8) {
// This unwraps correctly
let args_des: Vec<u8> = serde_json::to_string(&args).unwrap().into_bytes();
// This also returns a Vec<u8>
let args_des = args.0;
// But when trying to extend, append or merge:
let init_fn_args = [
Into::<Vec<u8>>::into(args_des)[..],
serde_json::json!({ "market_creator_account_id": env::signer_account_id() })
.to_string()
.into_bytes()[..],
];
let promise = Promise::new("cc".to_string())
.create_account()
.deploy_contract(MARKET_CODE.to_vec())
.transfer(env::attached_deposit())
.function_call(
"new".to_string(),
init_fn_args, // FAILS with expected struct `std::vec::Vec`, found array `[[u8]; 2]`
0,
GAS_FOR_CREATE_MARKET,
);
// Also tried with
let init_fn_args = args_des.extend(
serde_json::json!({ "market_creator_account_id": env::signer_account_id() })
.to_string()
.into_bytes(),
);
let promise = Promise::new("cc".to_string())
.create_account()
.deploy_contract(MARKET_CODE.to_vec())
.transfer(env::attached_deposit())
.function_call(
"new".to_string(),
init_fn_args, // FAILS with expected struct `std::vec::Vec`, found `()`
0,
GAS_FOR_CREATE_MARKET,
);
}

最令人困惑的部分是expected struct 'std::vec::Vec', found '()'。我仍然不明白为什么它会导致()而不是Vec

第一次尝试的完整编译器错误:

error[E0308]: mismatched types
--> src/contract.rs:69:47
|
69 |             .function_call("new".to_string(), init_fn_args, 0, GAS_FOR_CREATE_MARKET);
|                                               ^^^^^^^^^^^^ expected struct `Vec`, found array `[[u8]; 2]`
|
= note: expected struct `Vec<u8>`
found array `[[u8]; 2]`

第二次尝试的完整编译器错误:

error[E0308]: mismatched types
--> src/contract.rs:69:47
|
69 |             .function_call("new".to_string(), init_fn_args, 0, GAS_FOR_CREATE_MARKET);
|                                               ^^^^^^^^^^^^ expected struct `Vec`, found `()`
|
= note: expected struct `Vec<u8>`
found unit type `()`

第一个版本不起作用,因为[...]创建的是数组,而不是Vec。要修复它,您应该使用vec![...]

第二个版本不起作用,因为Vec::extend()有副作用,因此不返回值。(这很像Python,其中list.appendlist.sort返回None。(要修复它,应该调用args_des.extend(...whatever...),然后使用args_des而不是init_fn_args(或者在调用extend()之后声明let init_fn_args = args_des;(。

感谢您的回答,最终奏效的是:

pub fn merge(&mut self, args: Base64VecU8) -> Promise {
let mut init_args: Value = serde_json::from_slice(&args.0.as_slice()).unwrap();
init_args.as_object_mut().unwrap().insert(
"another_arg".to_string(),
Value::String(env::signer_account_id().to_string()),
);
// ... 

最新更新