I have been using structs like:

contract gas {

    struct example { 
       uint256 num;
       string name;    


I want to use an instance of other Contract in struct like:

contract token {

   struct example2 {
     gas g1; //instance of gas
     uint256 num;


Is it possible to use contract gas' g1 instance in struct of contract token (and later instantiate it when instantiating the example2 struct)? disclaimer: Im new in solidity (like 3 days new) so go easy! :)


Yes, it's possible. See this example

pragma solidity ^0.4.20;

contract ContractA {
    uint num;

    function ContractA(uint n) public {
        num = n;

    function get() public view returns(uint) {
        return num;

contract ContractB {

    struct Info {
        ContractA ainstance;
    mapping(uint => Info) infoMapping;
    uint length;

    function ContractB() public {


    function create(uint n) public {
        infoMapping[length] = Info(
            new ContractA(n)

    function get(uint index) public view returns(uint) {
        return infoMapping[index].ainstance.get();


the contract instance is just an address, so it can be save either explicitly or saving the address and cast it later. A revert exception will be thrown in case you're trying to perform operation that are not allowed in the contract (eg not existing methods)

| improve this answer | |
  • Perfect. Also it should be more expensive to create this struct since it acquires more storage space? – blockwala Apr 11 '18 at 8:42
  • you're saving the contract instance (address) with is 20 bytes. You can see the instance also as address ainstance – mirg Apr 11 '18 at 8:45
  • so every time "new ContractA(n)" is called a new address is assigned? I thought it would create storage on blockchain for the instance and not assign a new address? (much like java classes instance stored in heap memory ) – blockwala Apr 11 '18 at 10:00
  • yes, you create new storage on the blockchain with the data you save in the linked contract. I meant, in the original one, you would have only a reference. – mirg Apr 11 '18 at 10:03
  • 1
    yes, no issue with that. Either mapping(uint => ContractA) or mapping(uint => address) are fine (in the second case you need to cast the address to use the contract) – mirg Apr 12 '18 at 9:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.