[Ethereum] Member “name” not found or not visible after argument-dependent lookup in string storage ref

addressesmappingremixsoliditystruct

I have code like this and I want to set my name, surname and age in my struct so I want to set them and get them using with my functions

here's my code :


pragma solidity >=0.4.0 <0.7.0;

contract NewHello{
    address owner;
    
    constructor()public{
        owner = msg.sender;
    }
    
    modifier onlyOwner (){
        require(msg.sender == owner);
        _;
    }
    
    struct user{
        string name;
        string surname;
        uint age;
    }
    
    user[] new_user;
    mapping(address => string) public users; // contains a name for every address
    
    function updateUser(address _address, string memory name,string memory surname,uint age) public onlyOwner {
        user memory new_user = user(name,surname,age);
        users[_address] = user(name,surname,age);
        
    }
    function getUser(address _address) public view returns(string memory name ,string memory surname,uint age) {
        //if(users[_address].age == 0) throw;
        return (users[_address].name,users[_address].surname,users[_address].age); 
    }
}

I get 2 errors first one is :

TypeError: Type struct NewHello.user memory is 
not implicitly convertible to expected type string storage ref. 
users[_address] = user(name,surname,age);
                  ^--------------------^

TypeError: Member "name" not found 
or not visible after argument-dependent lookup in string storage ref.

anyone can help me please ?

Best Answer

Use a mapping like:

mapping(address => user) public users

Each address will have a user. You can improve that if you use msg.sender instead of address (function parameter), because you don't need to provide the address, and each user can change his data and see it (you need to remove the onlyOwner modifier in that case).

pragma solidity >=0.4.0 <0.7.0;

contract NewHello{ 

    address owner;

    constructor()public{
        owner = msg.sender;
    }

    modifier onlyOwner (){
        require(msg.sender == owner);
        _;
    }

    struct user{
        string name;
        string surname;
        uint age;
    }
    mapping(address => user) public users; // contains a user for every address

    function updateUser(address _address, string memory name, string memory surname, uint age) public onlyOwner {
        users[_address] = user(name, surname, age);
    }

    function getUser(address _address) public view returns(string memory name, string memory surname, uint age) {
         //if(users[_address].age == 0) throw;
        return (users[_address].name, users[_address].surname, users[_address].age);        
    }
}
Related Topic