Solidity
在字元串儲存引用中進行參數相關查找後,成員“名稱”未找到或不可見
我有這樣的程式碼,我想在我的結構中設置我的名字、姓氏和年齡,所以我想設置它們並讓它們與我的函式一起使用
這是我的程式碼:
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); } }
我得到 2 個錯誤,第一個是:
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.
任何人都可以幫助我嗎?
使用如下映射:
mapping(address => user) public users
每個地址都會有一個使用者。如果您使用msg.sender而不是地址(函式參數),您可以改進這一點,因為您不需要提供地址,並且每個使用者都可以更改他的數據並查看它(
onlyOwner
在這種情況下您需要刪除修飾符) .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); } }