Amiya Behera
Amiya Behera

Reputation: 2270

How to debug print NEAR protocol collections?

I'm having a hard time pretty-printing the NEAR protocol collections. I believe the best approach is to implement Debug for Map, Set, and Vector. Here's what I think I should be doing:

 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

If this is the wrong approach, how do I use println! to print out the contents of these collections?

Upvotes: 2

Views: 235

Answers (2)

Vlad Frolov
Vlad Frolov

Reputation: 7746

Here is the PR adding Debug implementation on the Vector collection. Feel free to add and send PR for adding Debug implementations for other collections.

As pointed out, you cannot implement a foreign trait for a foreign type, so you have 3 options:

  1. Contribute Debug impls to near-sdk
  2. Write a wrapper-types around the collections and impl Debug traits for them
  3. Use .to_vec() / .iter().collect::<HashMap>() methods explicitly and use them to pretty-print

Upvotes: 2

mikeDOTexe
mikeDOTexe

Reputation: 487

I believe you're taking a different approach than what you're aiming to do. As I understand it, you want to pretty-print this as you learn how to use these collections. Here are examples of the three collections you mentioned. Using each collections' .to_vec() you can see the results nicely when you run tests.

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());

If you then run cargo test -- --nocapture in your project you'll see output like this:

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

Upvotes: 3

Related Questions