Rust canister init function not called

I have a simple canister with the code like this

static mut TOKEN: Option<VotingToken> = None;

#[init]
fn init() {
    ic_cdk::print("!!! Calling init");

    unsafe {
        TOKEN = Some(VotingToken {
            name: "Default token".into(),
            balances: HashMap::new(),
        });
    }
}

But it seems like init() function is not called automatically after canister deployment. What am I doing wrong?

Another question: on the docs site there are several rust canister tutorials, two of which propose different storage management approaches (Adding and searching simple records :: Internet Computer / Incrementing a counter :: Internet Computer). What’s the difference?

2 Likes

Nevermind, was using the old version of DFX.

But the second question still matters.

Hm… it looks like it doesn’t get called on upgrade also.
After a canister upgrade there is no TOKEN anymore - it is uninitialized.

dfx 0.7.0

Yes, there are too few examples about rust canister.

about your first question, I run in 0.7.0 dfx and it inits succeed:

#[init]
fn init() {
    unsafe {
        COUNTER = Some(candid::Nat::from(0));
    }
}
sudo dfx canister call hello_rs get
(0)

the result is (0), not (null).

The second question I am also very confused, when do I need to choose different storage? What are their advantages and disadvantages.

The problem I have is that if I want to enter a parameter during initialization, I don’t know how to do it:

#[init]
fn init(a : candid::Nat) {
    unsafe {
        COUNTER = Some(candid::Nat::from(a));
    }
}

the results:

sudo dfx canister install hello_rs --argument='(1)' -m=reinstall
Reinstalling code for canister hello_rs, with canister_id ryjl3-tyaaa-aaaaa-aaaba-cai
The invocation to the wallet call forward method failed with the error: An error happened during the call: 5: Canister ryjl3-tyaaa-aaaaa-aaaba-cai trapped explicitly: Custom("No more values to deserialize")

sudo dfx canister install hello_rs -m=reinstall
Reinstalling code for canister hello_rs, with canister_id ryjl3-tyaaa-aaaaa-aaaba-cai
The invocation to the wallet call forward method failed with the error: An error happened during the call: 5: Canister ryjl3-tyaaa-aaaaa-aaaba-cai trapped explicitly: Custom("No more values to deserialize")

change the did file to:

service : (nat) -> {
  "increment": () -> ();
  "get": () -> (nat) query;
  "set": (nat) -> ();
}

and try dfx build --all

1 Like