Warning: Function state mutability can be restricted to pure function
Asked Answered
B

1

20

I am new to solidity and I have been trying to print out simple messages using functions in solidity, but I have failed to deploy successfully, and there is an error that I can not figure out what's wrong.

This is what I have tried so far:

 pragma solidity ^0.6.0;
    
    contract test {
        
        string public _feedback;
        
        function reply(string memory feedback) public
        {
           feedback = "Well done!";
        }
    }

The error I am receiving is "Warning: Function state mutability can be restricted to pure function"

Butyraceous answered 30/12, 2020 at 0:23 Comment(3)
Are you sure that's what's keeping you from deploying successfully? It's a warning, not an error. It's just suggesting you mark the function as pure, which is a good idea.Pritchett
Ah my mistake, I am able to deploy it, but the output is not as expected, the expected output is: reply | Well done! But right now the output is: reply | string _feedbbackButyraceous
A couple of problems here. You have two string variables here: One string in storage called _feedback, which you neither read nor write to, and one in memory called feedback, to which you immediately assign the hard-coded value "Well done!" in the function. The string provided as an argument is never used. In addition, if you want the function to return something (say, feedback) you need to specify function reply(string memory feedback) public returns(string feedback); Could you give us an idea of how you'd like this contract to behave?Brahmanism
J
23

The compiler simply WARNS that the result of the execution of the function reply is fixed and "canonically" this can be indicated by adding a pure specifier to it:

        function reply(string memory feedback) public pure
        {
           feedback = "Well done!";
        }

But even without this change, the contract will be compiled and created correctly. Only in its current form, you will not be able to understand in any way what it is working out :-)

Junto answered 30/12, 2020 at 5:53 Comment(1)
I replaced "view" with "pure" in order to remove the warning!Tantivy

© 2022 - 2024 — McMap. All rights reserved.