5 请问怎么给struct里的mapping里的struct赋值。

如截图所示,我的struct City里有个goods mapping,而这个mapping的value值又是一个struct。我尝试用如图所示的方法给这个struct赋值,但是报错,我猜应该是因为这个goods是在City里的,不能为外部所用。所以我想请问下,这种情况下怎么给这个goods赋值呢? image.png

我的代码如下:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.0 <0.9.0;

contract Market {
    struct City {
        uint256 cityID;
        string cityName;
        mapping(uint256 => SingleGoods) goods;
    }
    mapping(uint256 => City) citys;

    struct SingleGoods {
        string name;
        uint256 price;
        uint256 qua;
    }

    function init(
        uint256 _cityID,
        string memory _cityName,
        uint256 _goodsID,
        string memory _goodsName,
        uint256 _goodsPrice,
        uint256 _goodsQua
    ) public {
        City storage city1 = citys[_cityID];
        city1.cityID = _cityID;
        city1.cityName = _cityName;
        SingleGoods storage singleGoods1 = goods[_goodsID];
        singleGoods1.name = _goodsName;
        singleGoods1.price = _goodsPrice;
        singleGoods1.qua = _goodsQua;
        city1.goods = singleGoods1;
    }
}
请先 登录 后评论

最佳答案 2022-03-13 16:54

city1.goods[_goodsID]这么用

contract Market {
    struct City {
        uint256 cityID;
        string cityName;
        mapping(uint256 => SingleGoods) goods;
    }
    mapping(uint256 => City) citys;

    struct SingleGoods {
        string name;
        uint256 price;
        uint256 qua;
    }

    function init(
        uint256 _cityID,
        string memory _cityName,
        uint256 _goodsID,
        string memory _goodsName,
        uint256 _goodsPrice,
        uint256 _goodsQua
    ) public {
        City storage city1 = citys[_cityID];
        city1.cityID = _cityID;
        city1.cityName = _cityName;
        SingleGoods storage singleGoods1 = city1.goods[_goodsID];
        singleGoods1.name = _goodsName;
        singleGoods1.price = _goodsPrice;
        singleGoods1.qua = _goodsQua;
        //city1.goods = singleGoods1;
        /* City storage city1 = citys[_cityID];
        city1.cityID = _cityID;
        city1.cityName = _cityName;
        SingleGoods memory singleGoods1 = city1.goods[_goodsID];
        singleGoods1.name = _goodsName;
        singleGoods1.price = _goodsPrice;*/
        //citys[_cityID] = city1;
        //singleGoods1.qua = _goodsQua;
        //city1.goods = singleGoods1;
    }
}
请先 登录 后评论

其它 2 个回答

jackson
请先 登录 后评论
wess
请先 登录 后评论
  • 3 关注
  • 0 收藏,2809 浏览
  • happypl 提出于 2022-03-13 16:07