0

For the following struct, I store the author of a post as the AccountId of the content creator which requires a default value. I cannot for the life of me figure out the proper syntax to handle this as nothing seems to work. Could I get a proper example please?

#[derive(Debug, Clone, PartialEq, Encode, Decode, scale_info::TypeInfo)]
struct Post<AccountId> {
    author: AccountId,
}

impl<AccountId> Default for Post<AccountId> {
    fn default() -> Self {
        Post: "default address here",
    }
}

I have tried using string, string.into(), etc. Could I please get the proper way to do this?

2 Answers 2

1

First, be careful with default AccountIds. It was removed from Substrate, so make sure you understand the need for a default and the risks and that you choose it wisely.

It depends which AccountId you've chosen, but it's usually some variant of the MultiAddress. Assuming that it's a 32 byte AccountId, you'd need to provide a [u8; 32].

Note that the SS58 address includes a prefix, the 32 byte AccountId, and a checksum, so it actually has more information than just the AccountId. This is handy for address validation and UI rendering.

3
  • I do. The accountid needs to be a part of the post struct tho. The workaround is nightmarish, especially on the frontend. Its simpler, easier, and more efficient to include as part of the struct. And because this is the case, I need to impl default for an accountid. So, would that look like this: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ?
    – Aaron Ely
    Nov 19 at 21:38
  • 2
    Using 0x0… is a hack, not a proper fix. If there is no AccountId then maybe Post should use Option<AccountId>? Nov 20 at 15:11
  • Could you maybe provide an example please? I'm specifically not sure where to add the option tag.
    – Aaron Ely
    Nov 20 at 23:41
0

Depending on your circumstances it could be better to use the OnEmpty of your StorageValue or an OptionQuery.

Your Rust syntax looks off to me:

#[derive(Debug, Clone, PartialEq, Encode, Decode, scale_info::TypeInfo)]
struct Post<AccountId> {
    author: AccountId,
}

impl<AccountId> Default for Post<AccountId> {
    fn default() -> Self {
        Self { author: "default address here" }
    }
}
1
  • Can you show an example of what using option looks like?
    – Aaron Ely
    Nov 20 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.