2

Is there a way to create pseudo default function parameters in rust? I'd like to do something like

pub struct Circular<T> {
    raw: Vec<T>,
    current: u64
}

impl<T> Circular<T> {
    pub fn new(t_raw: Vec<T>, t_current=0: u64) -> Circular<T> {
        return Circular { raw: t_raw, current: t_current };
    }

I'd like to have the option of settings the current variable, but it won't always be needed to be set. Is this a possible thing to do in Rust?

0

1 Answer 1

5

No, Rust doesn't support default function arguments. You have to define different methods, or in case of struct initialization (your example) you can use the struct update syntax like this:

use std::default::Default;

#[derive(Debug)]
pub struct Sample {
    a: u32,
    b: u32,
    c: u32,
}

impl Default for Sample {
    fn default() -> Self {
        Sample { a: 2, b: 4, c: 6}
    }
}

fn main() {
    let s = Sample { c: 23, .. Sample::default() };
    println!("{:?}", s);
}
Sign up to request clarification or add additional context in comments.

4 Comments

How about if my members are module private? Do I just need to create multiple methods like new and new_default? There's no function overloading either right? EDIT: or I could make the current member mandatory as opposed to two functions I guess
There is no function overloading because Rust use function names to derive types (function overloading requires the opposite).
Also notice that you can set Sample fields to an Option type.
This is a great answer, and I encourage you to cross-post it to the linked duplicate!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.