Programing

Rust 구조체에서 변수를 초기화하는 더 빠르고 짧은 방법이 있습니까?

lottogame 2020. 10. 17. 09:01
반응형

Rust 구조체에서 변수를 초기화하는 더 빠르고 짧은 방법이 있습니까?


다음 예제에서 필자는 필드 선언에서 구조체의 각 필드에 값을 할당하는 것을 선호합니다. 또는 각 필드에 대해 하나의 추가 문을 사용하여 필드에 값을 할당합니다. 내가 할 수있는 것은 구조체가 인스턴스화 될 때 기본값을 할당하는 것뿐입니다.

더 간결한 방법이 있습니까?

struct cParams {
    iInsertMax: i64,
    iUpdateMax: i64,
    iDeleteMax: i64,
    iInstanceMax: i64,
    tFirstInstance: bool,
    tCreateTables: bool,
    tContinue: bool,
}

impl cParams {
    fn new() -> cParams {
        cParams {
            iInsertMax: -1,
            iUpdateMax: -1,
            iDeleteMax: -1,
            iInstanceMax: -1,
            tFirstInstance: false,
            tCreateTables: false,
            tContinue: false,
        }
    }
}

트레이 트를 구현하여 구조체에 대한 기본값을 제공 할 수 있습니다 Default. default기능은 현재처럼 보일 것입니다 new기능 :

impl Default for cParams {
    fn default() -> cParams {
        cParams {
            iInsertMax: -1,
            iUpdateMax: -1,
            iDeleteMax: -1,
            iInstanceMax: -1,
            tFirstInstance: false,
            tCreateTables: false,
            tContinue: false,
        }
    }
}

그런 다음 기본값이 아닌 값만 제공하여 구조체를 인스턴스화 할 수 있습니다.

let p = cParams { iInsertMax: 10, ..Default::default() };

With some minor changes to your data structure, you can take advantage of an automatically derived default implementation. If you use #[derive(Default)] on a data structure, the compiler will automatically create a default function for you that fills each field with its default value. The default boolean value is false, the default integral value is 0.

An integer's default value being 0 is a problem here since you want the integer fields to be -1 by default. You could define a new type that implements a default value of -1 and use that instead of i64 in your struct. (I haven't tested that, but it should work).

However, I'd suggest to slightly change your data structure and use Option<i64> instead of i64. I don't know the context of your code, but it looks like you're using the special value of -1 to represent the special meaning "infinite", or "there's no max". In Rust, we use an Option to represent an optionally present value. There's no need for a -1 hack. An option can be either None or Some(x) where x would be your i64 here. It might even be an unsigned integer if -1 was the only negative value. The default Option value is None, so with the proposed changes, your code could look like this:

#[derive(Default)]
struct cParams {
    iInsertMax: Option<u64>,
    iUpdateMax: Option<u64>,
    iDeleteMax: Option<u64>,
    iInstanceMax: Option<u64>,
    tFirstInstance: bool,
    tCreateTables: bool,
    tContinue: bool,
}

let p = cParams { iInsertMax: Some(10), ..Default::default() };

참고URL : https://stackoverflow.com/questions/19650265/is-there-a-faster-shorter-way-to-initialize-variables-in-a-rust-struct

반응형