如何调试打印 NEAR 协议集合?

How to debug print NEAR protocol collections?

我很难漂亮地打印 NEAR 协议集合。我相信最好的方法是为 Map, Set, and Vector 实施调试。这是我认为我应该做的:

 use std::fmt;    
 impl fmt::Debug for Map {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 
      // How do I fill this out?
    } 
 }

https://docs.rs/near-sdk/0.10.0/near_sdk/collections/index.html

如果这是错误的做法,我该如何使用println!打印出这些集合的内容?

我相信您采用的方法与您的目标不同。据我了解,您希望在学习如何使用这些集合时将其漂亮地打印出来。以下是您提到的三个集合的示例。使用每个集合的 .to_vec() 您可以在 运行 测试时很好地看到结果。

use near_sdk::{collections::Map, collections::Vector, collections::Set};

…

// you can place this inside a test

let mut my_near_vector: Vector<String> = Vector::new(b"something".to_vec());
my_near_vector.push(&"aloha".to_string());
my_near_vector.push(&"honua".to_string());
println!("Vector {:?}", my_near_vector.to_vec());

let mut my_near_map: Map<String, String> = Map::new(b"it's a dictionary".to_vec());
my_near_map.insert(&"aardvark".to_string(), &"a nocturnal burrowing mammal with long ears".to_string());
my_near_map.insert(&"beelzebub".to_string(), &"a fallen angel in Milton's Paradise Lost".to_string());
println!("Map {:?}", my_near_map.to_vec());

let mut my_near_set: Set<String> = Set::new(b"phonetic alphabet".to_vec());
my_near_set.insert(&"alpha".to_string());
my_near_set.insert(&"bravo".to_string());
println!("Set {:?}", my_near_set.to_vec());

如果你在你的项目中 运行 cargo test -- --nocapture 你会看到这样的输出:

running 1 test
Vector ["aloha", "honua"]
Map [("aardvark", "a nocturnal burrowing mammal with long ears"), ("beelzebub", "a fallen angel in Milton\'s Paradise Lost")]
Set ["alpha", "bravo"]
test tests::demo ... ok

Here is the PR 在 Vector 集合上添加调试实现。随意添加和发送 PR 以添加其他集合的调试实现。

如前所述,您不能为外部类型实现外部特征,因此您有 3 个选择:

  1. 为near-sdk贡献Debug impls
  2. 围绕集合编写包装器类型并为它们实现调试特征
  3. 显式使用 .to_vec() / .iter().collect::<HashMap>() 方法并使用它们进行漂亮打印