What role does the Solidity constructor play?

Asked 2 years ago, Updated 2 years ago, 89 views

I can't tell the difference between test_1 and test_2. (If you create a function that calls testMessage, they both work the same way.)

 contract test_1 {
  US>//#string testMessage="Hello, world!";
}

contract test_2 {
  US>string testMessage;
    constructor(){
      testMessage="Hello, world!";
    }
}

As I mentioned earlier, when I call testMessage, both of them show Hello, world properly.

function getMessage()public view returns(string){
  return testMessage;
}

execution results:

Hello, world!

I know the constructor has a special meaning, but I don't know exactly what role it has.

solidity

2022-09-30 19:17

1 Answers

It will only run once, as described in the documentation below.

https://solidity-jp.readthedocs.io/ja/latest/contracts.html

When a contract is created, the constructor (function declared with the constructor keyword) runs only once.


2022-09-30 19:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.