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?

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177

1 Answers1

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);
}
eulerdisk
  • 4,299
  • 1
  • 22
  • 21
  • 1
    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 – Syntactic Fructose Jul 11 '15 at 21:08
  • 1
    There is no function overloading because Rust use function names to derive types (function overloading requires the opposite). – eulerdisk Jul 11 '15 at 21:11
  • Also notice that you can set `Sample` fields to an [Option](https://doc.rust-lang.org/std/option/) type. – kopiczko Jul 12 '15 at 09:27
  • This is a great answer, and I encourage you to cross-post it to the linked duplicate! – Shepmaster Jul 12 '15 at 15:37