Add function to pre-existing struct

Viewed 861

I want to add my own function to a pre-existing struct which I don't have control over. As concrete example I want to to create an instance of std::fs::File

let logfile = std::fs::OpenOptions::new().create(true).open("file.txt").unwrap();

Then I want somehow create my own function fn foo() so that I'm later able to do logfile.foo();

I'm not sure if this is even possible, to be honest.

1 Answers

This is exactly what traits can be used for. See "Traits: Defining Shared Behavior" in the Rust Book.

In short, you can define your own trait Foo and add e.g. a fn foo(&self) method to it, and then impl Foo for std::fs::File, which allows you to call logfile.foo().

trait Foo {
    fn foo(&self);
}

impl Foo for File {
    fn foo(&self) {
        println!("foo");
    }
}

Also your OpenOptions is missing either a call to write() or append(). Otherwise, you'll receive an InvalidInput error.

Here's a complete example:

use std::fs::{File, OpenOptions};

trait Foo {
    fn foo(&self);
}

impl Foo for File {
    fn foo(&self) {
        println!("foo");
    }
}

fn main() {
    let logfile = OpenOptions::new()
        .write(true) // or `.append(true)`
        .create(true)
        .open("file.txt")
        .unwrap();

    logfile.foo();
}
Related