[Ethereum] the difference between an internal/external and public/private function in solidity

solidity

Currently reading solidity documentation: https://solidity.readthedocs.io/en/develop/types.html#function-types

By default, function types are internal, so the internal keyword can
be omitted. In contrast, contract functions themselves are public by
default, only when used as the name of a type, the default is
internal.

This does not make sense to me. How can a function be internal and public at the same time?

What does this part mean?

only when used as the name of a type

I know internal means functions can only be called within the contract and external can be called outside of the contract. So to me, internal is private and external is public but the documentation makes it sound like it can be public and internal at the same time?

So what is the difference, if any, between internal/external and public/private in regards to functions and how can the default be both internal and public at the same time?

Best Answer

The paragraph specifically mentions that only function types are by default internal, and contract functions are by default public, even though I agree the wording is a little bit confusing. It says nowhere that they are at the same time both public and internal.

I think that there is some confusion to what a function type is. The same way you specify the type for a 256 int variable with the keyword uint256, you can also specify the type of a variable that will hold a function. The only difference is that this type declaration is a little more complex since functions are more complex and it looks like this:

function (param types) {internal|external} [pure|constant|view|payable] [returns (return types)] varName;

You can then assign to the variable varName a function that has the same type that you defined. This is only possible inside another function.

As a very simple example:

contract Example{
    function(uint256) returns (uint256) varName;

    function simpleFunction(uint256 parameter) returns (uint256){
        return parameter;
    }

    function test(){
        varName = simpleFunction;
    }
}

Where varName is the variable of function type, while simpleFunction and test are normal contract functions

Just so you have a simple definition for all those access classifiers:

  • public - all can access
  • external - Cannot be accessed internally, only externally
  • internal - only this contract and contracts deriving from it can access
  • private - can be accessed only from this contract

As you can notice private is a subset of internal and external is a subset of public.

Related Topic