#How do I create a String or Symbol that contains the value of a variable?

10 messages · Page 1 of 1 (latest)

ornate nest
#

For example, if I wanted to make a map that contains 6 random numbers, and the keys i wanted should be something like rand_1, rand_2, etc.? How could I make that happen in Soroban? I think I know how I could do that in normal Rust, but I can't quite figure out how to do it with the soroban-sdk?

For example, if we were rolling 6 dice, like Yahtzee, here's some sample code of what I'm thinking about:

let mut return_map = map![&env];
for i in 1..=6 {
    let rolled_value = prng.u64_in_range(1..=6);
    // this line is where i'm not sure...
    return_map.set(symbol_short!("rand_{}", i), rolled_value);

I hope that at least somewhat makes sense. I know using the {} inside symbol_short doesn't work, but that's kindof what I've got in mind. I've also tried making the key using BytesN, and I can get it to "technically work" as the map keys, but what I'd really like is for the return map to give back the user (rand_1, 2), (rand_2, 4), (rand_3, 1), ...).

Would love to hear thoughts on how/if it's possible. Thanks!

left aurora
#

Symbol is generally not meant to be generated programmatically, String/Bytes is more appropriate for that. you can currently do string concatentaiton via copy to/from slice functions... but the real question is 'should you?'. storing just a number, or struct/tuple would be much simpler

#

though I suppose you can also create Symbols programmatically as well using Symbol::new.

#

I guess a use case for that would be some dynamic dispatch...

ornate nest
#

You're right, it would be simpler, but my curiosity started me down the road of figuring out how, and I couldn't look back lol

#

How would the copy to/from slice functions work for string concatenation? I played around with that and Symbol::new for a while but couldn't quite figure it out

left aurora
ornate nest
#

Awesome!! Thanks for pointing that out

left aurora
#

as usual, if there is a strong use case for doing string formatting on the host side, you can open a feature request for rs-soroban-env.

ornate nest
#

Thanks! I don't know that me farting around with it constitutes a strong use case, though 🤣