How to change a value inside a struct?

Daniela
Daniela
  • Updated

To change a value inside a struct in Flow, you would typically define a function within the contract that contains the struct. This function would be responsible for modifying the struct's properties.
Here's a basic example from the HelloWorld contract on Testnet:

pub contract HelloWorld {
pub var greeting: String

access(account) fun changeGreeting(newGreeting: String) {
self.greeting = newGreeting
}

init() {
self.greeting = "Hello, World!"
}
}

In this contract, the changeGreeting function is used to modify the greeting variable. Note that only the contract's owner or permitted accounts can modify the greeting.
If you want to change the state of the blockchain, you can use transactions. Transactions in Flow are pieces of Cadence code that can mutate the blockchain state.

Here's an example of a transaction that mints an NFT:

transaction(recipient: Address) {
let recipientCollectionRef: &{NonFungibleToken.CollectionPublic}
let mintingIDBefore: UInt64

prepare(signer: AuthAccount) {
self.mintingIDBefore = ExampleNFT.totalSupply
self.recipientCollectionRef = getAccount(recipient)
.getCapability(ExampleNFT.CollectionPublicPath)
.borrow<&{NonFungibleToken.CollectionPublic}>()
?? panic("Could not get receiver reference to the NFT Collection")
}

execute {
let currentIDString = self.mintingIDBefore.toString()
ExampleNFT.mintNFT(
recipient: self.recipientCollectionRef,
name: "Example NFT #".concat(currentIDString),
description: "Example description for #".concat(currentIDString),
thumbnail: "https://robohash.org/".concat(currentIDString),
royalties: []
)
}

post {
self.recipientCollectionRef.getIDs().contains(self.mintingIDBefore): "The next NFT ID should have been minted and delivered"
ExampleNFT.totalSupply == self.mintingIDBefore + 1: "The total supply should have been increased by 1"
}
}

In this transaction, the mintNFT function from the ExampleNFT contract is called to mint a new NFT and deposit it into the recipient's collection.

For more information, you can refer to our Flow documentation and this helpful guide.