I am trying to fetch caller address in ink smart contract to apply some checks.
let owner = self._check_token_exists(&id)?;
let caller = Self::env().caller();
I am confused which one i should use ?
I am trying to fetch caller address in ink smart contract to apply some checks.
let owner = self._check_token_exists(&id)?;
let caller = Self::env().caller();
I am confused which one i should use ?
In Rust, there is a distinction between self (lowercase) and Self (uppercase):
1- self (lowercase):
In method definitions, self refers to the current instance of a struct, enum, or trait implementation on which the method is being called. It allows you to access the fields and methods of the current instance. For example, if you have a struct called MyStruct with a method my_method, you can access the fields of the struct using self.field_name within the method.
2- Self (uppercase):
In traits and associated items, Self refers to the implementing type itself. It is used to specify that the implementing type will be used or returned. When you define a trait, you can use Self to refer to the implementing type instead of specifying the concrete type explicitly. This allows for more flexibility when implementing the trait for different types. For example, if you have a trait called MyTrait with an associated function new, you can use Self as the return type to indicate that the implementing type will be returned from the function. Here's an example to illustrate the difference:
struct MyStruct {
value: i32,
}
impl MyStruct {
fn my_method(&self) {
println!("Value: {}", self.value);
}
}
trait MyTrait {
fn new() -> Self;
}
struct AnotherStruct;
impl MyTrait for AnotherStruct {
fn new() -> Self {
AnotherStruct
}
}
fn main() {
let my_struct = MyStruct { value: 42 };
my_struct.my_method();
let another_struct: AnotherStruct = MyTrait::new();
}
In the example above, self is used within the my_method method to refer to the current instance of MyStruct. Self is used within the MyTrait trait to refer to the implementing type, which allows different types (such as AnotherStruct) to implement the trait and provide their own implementation of the associated function new.