'Array.length as key for a function (solidity)
My apologies for the newbie question however I am attempting to learn coding and have no other means of finding the solution. I am looking for a way to have a unique key added to the outcome of a function so I can have other iterations of that same function to refer to it if needed.
Please find the code below. When I run the code as it stands it keep asking for a value to be input by the user while I am looking for the code to not ask the user but to use the value that is produced from the gettid() function.
As I am clearly very new to coding so I am also open to suggestions as to improve on the key identifier (it needs to be unique and although my approach is simple it should produce unique values).
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract example{
struct Input{
uint256 gettid;
string title1;
string title2;
string title3;
string title4;
string title5;
}
Input[] public inputsArray;
function gettid() public view returns(uint256) {
return inputsArray.length;
}
function addinput(
uint256 _gettid,
string memory _title1,
string memory _title2,
string memory _title3,
string memory _title4,
string memory _title5
) public {
inputsArray.push(Thread(_gettid, _title1, _title2, _title3, _title4, _title5));
}}
Solution 1:[1]
You can call the gettid() function and store the return value in a temporary uint and then push the temp uint to the array. Something like this:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract example{
struct Input{
uint256 gettid;
string title1;
string title2;
string title3;
string title4;
string title5;
}
Input[] public inputsArray;
function gettid() public view returns(uint256) {
return inputsArray.length;
}
function addinput(
string memory _title1,
string memory _title2,
string memory _title3,
string memory _title4,
string memory _title5
) public {
uint256 _nextId = gettid();
inputsArray.push(Thread(_nextId, _title1, _title2, _title3, _title4, _title5));
}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Svante |
