References
let hello = "Hello"
// Create a reference to the "Hello" string, typed as a `String`
//
let helloRef: &String = &hello as &String
helloRef.length // is `5`
// Invalid: Cannot create a reference to `hello`
// typed as `&Int`, as it has type `String`
//
let intRef: &Int = &hello as &Int// Declare a resource interface named `HasCount`,
// that has a field `count`
//
resource interface HasCount {
count: Int
}
// Declare a resource named `Counter` that conforms to `HasCount`
//
resource Counter: HasCount {
pub var count: Int
pub init(count: Int) {
self.count = count
}
pub fun increment() {
self.count = self.count + 1
}
}
// Create a new instance of the resource type `Counter`
// and create a reference to it, typed as `&Counter`,
// so the reference allows access to all fields and functions
// of the counter
//
let counter <- create Counter(count: 42)
let counterRef: &Counter = &counter as &Counter
counterRef.count // is `42`
counterRef.increment()
counterRef.count // is `43`Last updated