About using List as the return result, there is null in the problem

Hello everybody!
When I use List as the return result, if there are >1 elements in the List result, then there will be an extra null in the list similar to (opt record {record {status=variant {relate}; owner=principal “rwlgt-iiaaa-aaaaa- aaaaaa-cai”; relateTime=1635842367169199000}; null}), please ask how can I get a clean list, that is, whether there are elements or not, I don’t want a null in it, at least when it is displayed ()

public shared func getRelates(address:?Text) :async List<ETHRelate>{
        var relateList :?List<ETHRelate> = ethRelates.get(msg.caller);
        var list = Option.get<List<ETHRelate>>(relateList,List.nil<ETHRelate>());
        if (address != null){
            var list = List.nil<ETHRelate>();
            List.iterate<ETHRelate>(list,func(obj:ETHRelate){
                if (?obj.address == address){
                    list := List.push<ETHRelate>(obj,list);
                };
            });
            return list;
        } else {
            return list;
        };
    };



(opt record {record {status=variant {relate}; owner=principal "rwlgt-iiaaa-aaaaa-aaaaa-cai"; relateTime=1635842367169199000; address="0x6865fC780d3267CE0F13d95eb8ec82b768C99475"; unRelateTime=null}; null})
1 Like

The List type is defined as

type List<T> = ?(T, List<T>)

so it is always terminated with a null value.

It is not a great type for public interfaces, I suggest to use arrays in the public interface (so use return type async [ETHRelate] and return list.toArray()), as this maps to Candid’s vec type, which is what users of your interface will likely expect.

4 Likes

I agree with you, thank you very much