0

So I have several functions in a struct which return a value:

fn a(&mut self) -> u8{
   //Do stuff
   return 0;
}
fn b(z: u8) -> u8{return z;}
fn c(&mut self) -> u8{
   //Do stuff
   return 2;
}

I want to know if there is a way to call a function from an array which can be accessed by other member for functions, so, for example:

static FUNCTIONS: [u8; 3] = [a(), b(some_value), c()];
// OR
let functions: [u8; 3] = [a(), b(some_value), c()];

So in summation, I would like to do something like this:

struct this_struct {
   value:u8
}

impl this_struct {
   // The array of functions could be placed here for member access

   fn a(&mut self) -> u8{
      //Do stuff with value
      return 0;
   }
   fn b(z: u8) -> u8{return z;}
   fn c(&mut self) -> u8{
      //Do stuff with value
      return 2;
   }
}

Basically, I just want to know if there is a way to call a function of a struct from an array in a way which will modify the struct's member variable. Is this possible? If so, how and where should I place the array?

2
  • What do you mean by value in b(value)? Should FUNCTIONS be per-object? Or value some known constant? Commented Jul 5, 2020 at 22:00
  • Please clarify your question. The title asks how to "create an array of functions", while the code you posted seems like it tries to initialize a global static array to values returned by associated functions.I can only guess you don't comfortable with Rust yet, in that case please go ahead and read the book. Commented Jul 5, 2020 at 22:02

1 Answer 1

1

What you are trying to do here is not an array of functions but an array of functions results. Then you must specify from what struct you use functions ex.

static FUNCTIONS: [u8; 3] = [this_struct::a(), this_struct::b(value), this_struct::c()];

Additionaly in statics you can only use constant functions

impl this_struct {
   const fn a() -> u8{return 0;}
   const fn b(z: u8) -> u8{return z;}
   const fn c() -> u8{return 2;}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Honestly, I think the question poster probably requires a lot more explanation. Where is that value coming from? What are associated and const functions? When do static globals make sense, and why are they bad most times? At least some links would be nice. Thank you for your first contribution though, keep it up!
Thanks for the answer! My question was more about how to create an array of functions which can modify a struct's member variables, and where to place said array. I edited the question to make more sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.