You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Remix Solidity实现序号查询学生信息的函数开发需求

解决方案:通过序号查询学生信息

原合约已维护了存储学生地址的数组student_Info,无需额外新增映射,直接基于现有结构就能实现按1起始序号查询的功能。核心思路是将输入的序号转换为数组索引(序号-1),再通过地址从映射中取出学生信息,同时要做参数合法性校验。

修改后的完整合约代码

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ReferenceTypes {
    address public owner;
    
    struct student {
        string Name;
        uint Age;
        string BirthPlace;
        uint8 Marks;
    }
    
    constructor() {
        owner = msg.sender;
    }
    
    mapping (address => student) public Info;
    address[] public student_Info;
    
    function addInfo(student memory _student, address _address) public {
        require(owner == msg.sender, "Only admin can add Info!!!");
        Info[_address] = _student;
        student_Info.push(_address);
    } 
    
    function count() public view returns(uint) {
        return student_Info.length;
    }

    // 新增:按1起始序号查询学生信息
    function getStudentByIndex(uint _index) public view returns(student memory) {
        // 校验序号合法性:不能小于1,不能超过当前学生总数
        require(_index >= 1 && _index <= student_Info.length, "Invalid student index");
        // 转换为数组的0起始索引
        address studentAddr = student_Info[_index - 1];
        return Info[studentAddr];
    }
}

关键说明

  • 参数校验:新增的getStudentByIndex函数首先检查输入的序号是否在有效范围内(1到学生总数之间),避免数组越界访问。
  • 索引转换:由于Solidity数组是从0开始的,所以将输入的1起始序号减1,得到对应的数组索引,再取出学生地址。
  • 复用现有结构:直接利用原合约的student_Info数组和Info映射,无需额外存储,节省链上资源。

内容的提问来源于stack exchange,提问作者CHIC4EVER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:01:01