1

Came across this script teaching people how to use library, but I don't understand why the function testFind should be external in the following script. The definition of external function is : external functions are part of the contract but can only be used externally and called outside the contract by the other contracts. But in this case, we are calling the testFind function from inside of Freedom contract. So why is the function external?
my 2nd question is why is the function inside the library internal? does it mean that the contract Freedom "inherit" the library?

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

library IndexOf{
    function findIndex(uint[] storage arr, uint x) internal view returns(uint){
        for (uint i=0; i<arr.length; i++){
            if (arr[i] == x){
                return i;
            }
        }
        revert("index not found");
    } 
}

contract Freedom{
    uint[] arr = [3,2,1];
    using IndexOf for uint[];
    function testFind(uint x) external view returns(uint y ){
        return arr.findIndex(x);
    }
}

Thank you for your patience!

2 Answers 2

0

Function visibility is determined in contract scope. There's no internal call of testFind (it is called only externally - from frontend or script or another contract for example) so it's external and not public.

Library func is not called from the outside , so it can be private/internal.

Check this question for better understanding.

0

The function testFind could be external because functions with external visibility could be called outside the function (if that's intended) and save gas compared to declared this as public. You can also call external functions with this.testFind(x) inside a contract.

The function inside the library is declared as internal most likely because the developer intends the function to only be called internally and it does not mean that the contract Freedom can "inherit" the library because libraries cannot be inherited.

See:

https://stackoverflow.com/questions/67590652/solidity-which-method-should-i-use-to-call-a-function-of-an-external-contract

https://coinsbench.com/solidity-101-introduction-to-libraries-in-solidity-b4555f2e0066#:~:text=Cannot%20be%20inherited%20%E2%80%94%20For%20the,implement%20fallback%20or%20payable%20functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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