Solidity 044 Interface

本文介绍了如何在Solidity中定义和实现接口IHelloWorld,以及如何通过Client合同调用HelloWorld合同的接口方法进行值的设置和获取。展示了接口在智能合约设计中的应用。
摘要由CSDN通过智能技术生成

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.9;

// Define an interface IHelloWorld. Interfaces are used to define contracts' external functions without implementing them.

interface IHelloWorld {

   // Declare an external function GetValue that, when implemented, will return a uint value.

   function GetValue() external view returns (uint);

   // Declare an external function SetValue that takes a uint _value as input.

   function SetValue(uint _value) external;

}

// Implement the IHelloWorld interface with a contract named HelloWorld.

contract HelloWorld is IHelloWorld {

  // Declare a private uint variable to store a simple integer value.

  uint private simpleInteger;

  // Implement the GetValue function defined in the IHelloWorld interface.

  // This external view function returns the current value of simpleInteger.

  function GetValue() external view override returns (uint) {

    return simpleInteger;

  }

  // Implement the SetValue function defined in the IHelloWorld interface.

  // This external function updates the value of simpleInteger.

  function SetValue(uint _value) external override {

   simpleInteger = _value;

  }

}

// Define a contract named Client to demonstrate interaction with the HelloWorld contract via the IHelloWorld interface.

contract Client {

  // Define a public function that demonstrates setting and getting a value from the HelloWorld contract.

  function GetSetIntegerValue() public returns (uint) {

    // Instantiate a new HelloWorld contract and assign it to the interface type IHelloWorld.

    IHelloWorld myObj = new HelloWorld();

   

    // Set the value of simpleInteger in the HelloWorld contract to 100.

    myObj.SetValue(100);

   

    // Get the current value of simpleInteger from the HelloWorld contract, add 10 to it, and return the result.

    // Note: The original approach will work, but typically you'd interact with the contract directly

    // if it's being created within the same transaction for efficiency.

    return myObj.GetValue() + 10;

  }

}

  • 16
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值