solidity TypeError: Data location can only be specified for array, struct or mapping types

当编译solidity合约代码报如下异常时,说明函数入参或函数返回或函数体中,用到的变量中,有引用类型的变量,此时需要注意指定变量的存储类型(calldata、memory、storage),其中包括了string类型的变量(引用类型变量)也同样需要注意设定存储类型。其它基本类型不要在入参和返回中画蛇添足,同样会导致报错。

示例,如下代码会导致报错

pragma solidity ^0.5.1;

contract ContractExp1{
    string public value;
    uint256 public count=0;

mapping(uint256 => Person) public people;

struct Person{
    string name;
    uint256 balance;
}


constructor() public{
    value='myValue';
}


function setPeople (string memory _name, uint256 memory _val) public {
    count=count+1;
    people[count]=Person(_name,_val);
    }
}

报错信息如下

正确的改法如下,如此程序和正常编译

function setPeople (string memory _name, uint256 _val) public {

这样修改的理由,在一开始就已经阐述,此处总结:

  1. 默认基本类型,不需要刻意指定 存储类型
  2. struct、动态数组、映射、string等引用类型必须指定存储类型,否则编译会报异常

猜你喜欢

转载自blog.csdn.net/m0_37298500/article/details/126976680