Solidity Struct Demo: Correcting Common Errors and Best Practices
There are several issues with the given code.
- There is a missing semicolon at the end of the line where the struct is defined.
- The struct instance ('b') should be defined inside a function or in the global scope, not directly in the contract body.
- The function names are all the same, which is not allowed. Each function should have a unique name.
- The return types of the functions are inconsistent. For the last function, the return type should be 'uint', not 'string memory'.
Here's the corrected code:
pragma solidity >=0.7.0 <0.9.0;
contract StructDemo {
struct Book {
string Name;
string publisher;
uint price;
uint pagecount;
}
Book b;
constructor() {
b = Book('aaa', 'bbb', 12, 13);
}
function getName() public view returns (string memory) {
return b.Name;
}
function getPublisher() public view returns (string memory) {
return b.publisher;
}
function getPrice() public view returns (uint) {
return b.price;
}
function getPageCount() public view returns (uint) {
return b.pagecount;
}
}
In this corrected code:
- The struct instance 'b' is defined inside the contract constructor.
- Each function has a unique name.
- The return types of the functions are consistent with the type of the respective struct member.
原文地址: https://www.cveoy.top/t/topic/pdo8 著作权归作者所有。请勿转载和采集!