2017-10-24 2 views
0

관련된 유형의 크기가되지 않기 때문에 옵션 <관련 유형>을 반환 할 수 없습니다 : 나는 연관된 유형 Bar이 크기해야하는 제약 조건이 할이 코드는 컴파일되지 않는 이유를 이해가 안

fn main() {} 

trait NotWorking { 
    // The associated type `Bar` must be sized 
    type Bar: ?Sized; 

    // Why does the compiler complain that Self::Bar is not sized? 
    // I have a trait bound that says it is! 
    fn notwoking() -> Option<Self::Bar>; 
} 

을하지만,

error[E0277]: the trait bound `<Self as NotWorking>::Bar: std::marker::Sized` is not satisfied 
    --> src/main.rs:17:5 
    | 
17 |  fn notwoking() -> Option<Self::Bar>; 
    |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `<Self as NotWorking>::Bar` does not have a constant size known at compile-time 
    | 
    = help: the trait `std::marker::Sized` is not implemented for `<Self as NotWorking>::Bar` 
    = help: consider adding a `where <Self as NotWorking>::Bar: std::marker::Sized` bound 
    = note: required by `std::option::Option` 

내가 그것을 작동하도록 노력하고, 이것에 조금을했다, 우리는 크기를 지정하지 않은하는 형식을 반환 할 수 없기 때문에, 내가 기대했다 (이 작동하는지 깜짝 놀랐다 : 컴파일러는 여전히 크기를 지정하지 않은 것 불평 실패 할 것임) :

fn main() {} 

trait Working { 
    type Bar; 

    // Why does this work? 
    // I would expect the compiler to complain the Self::Bar is not sized 
    fn woking() -> Self::Bar; 
} 

나는 여기 중요한 것을 분명히 놓치고 있습니다. 제가 전문가가 아니에요

required by `std::option::Option` 

하지만 컴파일러는 변종에 열거 OptionBar을 입력 레이아웃하는 방법을 알고 유형의 크기에 대한 정보를 필요로 추측 :

+0

oooh'? Sized' 대신'Sized'를 지정했을 때'NotWorking' 예제가 작동하고있는 것으로 나타났습니다. –

+3

'? Sized'는 크기를 정할 필요가 없음을 의미합니다 * : https://doc.rust-lang.org/std/marker/trait.Sized.html – Boiethios

답변

2

두 번째 예가 정확합니다. Sized으로 일반 매개 변수를 선언하는 방법은 명시적인 경계를 지정하지 않는 것입니다. Sized은 일] 적으로 Sized이 아닌 경우 일] 적으로 일] 적으로 일] 매개 변수에 대한 Y 인드로서 내재적으로 추가된다는 점에서 특 별합니다. 컴파일시 알려진 크기를 갖도록 제네릭 매개 변수를 요구하지 않으려는 경우 remove this implicit bound by writing ?Sized을 사용할 수 있습니다.

documentation for Sized도 참조하십시오.

0

대답은 마지막 문자열에 기억.

관련 문제