- Rust also supports struct that look similar to tuples called tuple struct.
- Tuple struct is similar to normal struct apart from not having a name assocaited with each field.
struct Color(i32, i32, i32);
struct Point(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);
print("{Colour is {}", black.0);
}
The above code shows how to create tuple struct and how to use it.
You can print the whole tuple in the terminal using a trait called debug:
#[derive(Debug)]
struct Color(i32, i32, i32);
fn main() {
let black = Color(0, 0, 0);
print("{Colour is {:?}", black.0);
}
- The output would be like given below:
Color(0,0,0)
- You can add methods for the struct using given below codes:
struct Color(i32, i32, i32);
impl Color{
fn describe(&self){
println!("{}, {} and {}", self.0, self.1, self.2);
}
fn twice(&self) -> Color{
Color(self.0 * 2, self.1 * 2, self.2 * 2)
}
fn make_twice(&mut self){
self.0 *= 2;
self.1 *= 2;
self.2 *= 2;
}
}
fn main() {
let black = Color(0, 0, 0);
}
- The keyword impl followed by the tuple struct is the structure for adding methods for the structure.
- You can add multiple impl for the same struct, for make your code more readable.
- The above methods can be called using below piece of codes:
fn main() {
let mut black = Color(0, 0, 0);
// simple tuple struct method call
black.describe();
// method call with a return type
let white: Point = black.twice();
// to mutate the tuple struct
black.make_twice();
}
- Assoicated functions: Associated functions don't take self as a paramter and they are not method as they don't have a instance of struct to work with.
- Unlike normal methods, associated functions are called using :: rather than . .
- A good example would be String::from().
- The code below show how to create an associated function for struct
struct Color(i32, i32, i32);
impl Color{
fn zero() -> Color{
Color(0,0,0)
}
}
fn main() {
let black = Color(0, 0, 0);
// instead of using the above code we can rewrite it using assocaited function
let black = Color::zero()
}
Comments
Post a Comment