Search code examples
motoko

Shared function has non-shared return type


Getting error Shared function has non-shared return type for returning Item for the get method.

How would one make Item shared or is there a better way going about returning properties/object

public type Item = {
    id: Nat;
    var name: Text;
};

actor Maas {
    var items: [Item] = [];

    ...

    public shared query func get(id: Nat) : async Item {
        return businesses[id - 1];
    };
};

Solution

  • I just started getting into Motoko but I dug a little bit into documentation.

    As I understood you need to make your type shared type (https://smartcontracts.org/docs/language-guide/language-manual.html#sharability)

    A type T is shared if it is:
    
    - an object type where all fields are immutable and have shared type, or
    
    - a variant type where all tags have shared type
    

    Since var is declares mutable variables (https://smartcontracts.org/docs/language-guide/mutable-state.html#_immutable_versus_mutable_variables) The type becomes non shared type.

    All there is need to be done is to remove var from the type Item

    public type Item = {
        id: Nat;
        name: Text;
    };
    
    actor Maas {
        var items: [Item] = [];
    
        ...
    
        public shared query func get(id: Nat) : async Item {
            return businesses[id - 1];
        };
    };