Understanding the features and security of objects

I am struggling with the basics of object security. If i have this code

struct S {
    x: i32
}

trait Trait: Sized {
    fn f(&self) -> i32 where Self: Sized;
}

fn object_safety_dynamic(x: Trait) {}

I get

fn object_safety_dynamic(x: Trait) {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `traits::Trait` cannot be made into an object
= note: the trait cannot require that `Self : Sized`

When I add / change :Sizedas a trait inheritance or binding, fI get slightly different error messages.

Can anyone explain:

  • Why does this particular example not work? The Trait Objects chapter says, “What makes a method object-safe? Each method must require that Self: Sized.” Isn't it full?

  • What is the difference between Trait: Sizedand where Self: Sized? (Well, yes, one inherits the trait, the other is associated with the parameter, but from the point of view of the Rust object?

  • What preferred change did I have to make object_safety_dynamic?

rustc 1.19.0-nightly (01951a61a 2017-05-20), .

- Follow Up:

.

trait TraitB {
    fn f(&self) -> i32 where Self: Sized;

    fn g<T>(&self, t:T) -> i32 where Self: Sized;
}
+2
2

? " " ", -? " Self: Sized ". ?

: -?

A Trait Object - - :

  • ,
  • .

, , , "", .

, , , , , , ; "" , , &TraitObject, &mut TraitObject Box<TraitObject>.

:

  • , , "" - ,
  • .

: Sized Self: Sized? (, , , , Rust?)

Rust . :

  • Trait: Sized , , Sized,
  • fn method(&self) where Self: Sized , , Sized.

: ; , Self: Sized , .

object_safety_dynamic?

. , , .

+6

Trait Sized - , . Trait - , object_safety_dynamic . , , Trait.

, :

trait Trait {
    fn f(&self) -> i32;
}

fn object_safety_dynamic(x: &Trait) {}

- - , . a Box<T> &T. , , .

+2

Source: https://habr.com/ru/post/1684077/


All Articles